例如,假设我有一个结构AdjacencyList
,我想在其中指定顶点存储的容器类型,以便用户可以选择Set
如果他们不想要重复,或Array
,如果他们这样做。
(我已经省略了类型的协议一致性,因为我的示例代码已经不正确了,许多必须符合容器类型。例如,Set
元素需要是Hashable
。)
public struct AdjacencyList<VertexType, EdgeType, VertexContainerType, EdgeContainerType> {
var vertices: VertexContainerType<VertexType>
...
}
答案 0 :(得分:1)
您遇到的问题是CollectionType
不是通用的。围绕您指出的特定问题的一种方法是让客户端指定容器类型,然后您可以提取实际的元素类型。
例如:
struct AdjacencyList<VertexContainerType: CollectionType, EdgeContainerType: CollectionType> {
var vertices: VertexContainerType
typealias VertexType = VertexContainerType.Generator.Element
typealias EdgeType = EdgeContainerType.Generator.Element
func printTypes() {
print("VertexType: \(VertexType.self)\nEdgeType: \(EdgeType.self)")
}
}
let a = AdjacencyList<Array<Int>, Array<Double>>(vertices: [Int]())
a.printTypes()
// Prints:
// VertexType: Int
// EdgeType: Double