ios - 错误 : type may not reference itself as a requirement associatedtype Suffix: SuffixableContainer where Suffix. 项目 == 项目

标签 ios swift generics protocols

当我在 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/

相关文章:

iphone - 如何从第二个 View Controller 以编程方式创建选项卡栏

ios - Swift 将多个 IBOutlet 放在一个数组中

swift - 在模型 I/O 中,提供的库中缺少记录的 API。解决方法是什么?

java - 代码模型 : generic types generation in a loop . 窄()?

ios - 返回上一个 Controller 并再次返回时如何获取视频的下载状态?

iphone - 如何使用 XMLParser 委托(delegate)解析 XML 属性

ios - 具有多个自定义单元格类型的 RxSwift TableView

ios - 为 UITabBarItem 设置操作

java - 继承方法返回引用类型

Scala 从泛型实例化一个具体类