作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
例如,假设我有一个结构体 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/
我是一名优秀的程序员,十分优秀!