简体   繁体   English

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

[英]How can I specify a CollectionType for a generic struct/class?

For example, say I have an struct AdjacencyList where I want to specify the type of container that the vertices are stored in such that the user can choose Set if they don't want duplicates, or Array if they do. 例如,假设我有一个结构AdjacencyList ,我想在其中指定存储顶点的容器的类型,以便用户可以选择“ Set如果不想复制)或“ Array如果需要)。

(I've omitted protocol conformances for the types since my example code is already incorrect as-is and many would have to be conformed to depending on the container type. For example, Set elements would need to be Hashable .) (我已经省略了类型的协议一致性,因为我的示例代码按原样已经是不正确的,并且根据容器类型必须要遵循许多协议一致性。例如, Set元素必须是Hashable 。)

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

The issue you are running into is that CollectionType is not generic. 您遇到的问题是CollectionType不是通用的。 One way around the specific issue you point out is to just have the client specify the container types and then you can extract the actual element types. 您指出的解决特定问题的一种方法是,仅让客户端指定容器类型,然后就可以提取实际的元素类型。

For example: 例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM