我试图在swift 3中创建一个通用的图结构。问题是编译器失败并显示以下消息:
While emitting IR SIL function ... for 'init' at .../Graph.swift:48:21
编译器指向的行是Edge
类的 init 方法:
public class Edge<T: Hashable, V: Vertex<T>> {
public var source: V
public var destination: V
public let weight: Double?
required public init(source: V, destination: V, weight: Double? = nil) {
self.source = source
self.destination = destination
self.weight = weight
}
}
我想我可能是泛型使用的问题。以下是涉及的类:
public class Vertex<T: Hashable> {
var data: T
required public init(data: T) {
self.data = data
}
}
extension Vertex: Hashable {
public var hashValue: Int {
return "(data)".hashValue
}
static public func ==(lhs: Vertex, rhs: Vertex) -> Bool {
return lhs.data == rhs.data
}
}
extension Vertex: CustomStringConvertible {
public var description: String {
return "(data)"
}
}
// MARK: - Edge
public enum EdgeType {
case directed, undirected
}
public class Edge<T: Hashable, V: Vertex<T>> {
public var source: V
public var destination: V
public let weight: Double?
required public init(source: V, destination: V, weight: Double? = nil) {
self.source = source
self.destination = destination
self.weight = weight
}
}
extension Edge: Hashable {
public var hashValue: Int {
return "(source)(destination)(weight)".hashValue
}
// We need to overload the equals operator because Hashable implements Equatable
static public func ==(lhs: Edge<T, V>, rhs: Edge<T, V>) -> Bool {
return lhs.source == rhs.source && lhs.destination == rhs.destination && lhs.weight == rhs.weight
}
}
这两个类由泛型AdjacencyList<T: Hashable, V: Vertex<T>, E: Edge<T, V>>
谢谢
无法告诉您代码崩溃的原因。您最好为此问题发送错误报告。但是我有一个解决方法:
public protocol VertexType: Hashable {
associatedtype DataType
var data: DataType { get set }
}
public class Vertex<T: Hashable>: VertexType {
public var data: T
required public init(data: T) {
self.data = data
}
}
extension Vertex {
public var hashValue: Int {
return "(data)".hashValue
}
static public func ==(lhs: Vertex, rhs: Vertex) -> Bool {
return lhs.data == rhs.data
}
}
extension Vertex: CustomStringConvertible {
public var description: String {
return "(data)"
}
}
// MARK: - Edge
public class Edge<V: VertexType> {
public var source: V
public var destination: V
public let weight: Double?
required public init(source: V, destination: V, weight: Double? = nil) {
self.source = source
self.destination = destination
self.weight = weight
}
}
extension Edge: Hashable {
public var hashValue: Int {
return "(source)(destination)(weight)".hashValue
}
// We need to overload the equals operator because Hashable implements Equatable
static public func ==(lhs: Edge<V>, rhs: Edge<V>) -> Bool {
return lhs.source == rhs.source && lhs.destination == rhs.destination && lhs.weight == rhs.weight
}
}
现在,您可以根据需要使用Vertex
子类:
public class IntVertex: Vertex<Int> {}
Edge(source: IntVertex(data: 1), destination: IntVertex(data: 2))
更新:
看起来这在 Swift 3.1 中得到了修复。至少类似的错误不再使Xcode 8.3崩溃。因此,更新您的Xcode可能就足够了。