如何为通用结构/类指定CollectionType?

时间:2016-05-02 07:02:44

标签: swift

例如,假设我有一个结构AdjacencyList,我想在其中指定顶点存储的容器类型,以便用户可以选择Set如果他们不想要重复,或Array,如果他们这样做。

(我已经省略了类型的协议一致性,因为我的示例代码已经不正确了,许多必须符合容器类型。例如,Set元素需要是Hashable。)

public struct AdjacencyList<VertexType, EdgeType, VertexContainerType, EdgeContainerType> {
    var vertices: VertexContainerType<VertexType>
    ...
}

1 个答案:

答案 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