gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 10:04:08 25 4
gpt4 key购买 nike

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

(我省略了类型的协议(protocol)一致性,因为我的示例代码本来就不正确,并且许多代码必须根据容器类型来遵守。例如,Set 元素将需要可哈希。)

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

最佳答案

您遇到的问题是 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

关于swift - 如何为通用结构/类指定 CollectionType?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36976721/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com