当我在 Playground xcode 9.2 上运行时,苹果文档代码中出现上述错误 https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Generics.html
部分:使用类型注释来约束关联类型
protocol Container {
associatedtype Item: Equatable
mutating func append(_ item: Item)
var count: Int { get }
subscript(i: Int) -> Item { get }
}
protocol SuffixableContainer: Container {
associatedtype Suffix: SuffixableContainer where Suffix.Item == Item
func suffix(_ size: Int) -> Suffix
}
他们的解释:在这个协议(protocol)中,Suffix是一个关联类型,就像上面Container例子中的Item类型。 Suffix 有两个约束:它必须符合 SuffixableContainer 协议(protocol)(当前正在定义的协议(protocol)),它的 Item 类型必须与容器的 Item 类型相同。
最佳答案
protocol SuffixableContainer: Container {
associatedtype Suffix: SuffixableContainer
// ...
}
对关联类型使用“递归约束”:关联
类型 Suffix
受限于封闭协议(protocol) SuffixableContainer
。
关联类型的递归约束已在 Swift 4.1 中实现,即该代码需要 Xcode 9.3(目前处于测试阶段)。
来自Swift CHANGELOG :
Swift 4.1
...
SE-0157 is implemented. Associated types can now declare "recursive" constraints, which require that the associated type conform to the enclosing protocol.
关于ios - 错误 : type may not reference itself as a requirement associatedtype Suffix: SuffixableContainer where Suffix. 项目 == 项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49490509/