swift - 我的类可以覆盖 Swift 中的协议(protocol)属性类型吗?

标签 swift protocols

protocol Parent {
     var children: [AnyObject] { get set }
}

class Foo {
}

class Bar: Parent { //error happens here
    var children = [Foo]()

    init() {}
}

我得到一个错误“Type 'Object' does not conform to protocol 'Parent'。我得到这个错误的原因是因为我将 child 定义为 Foo 的数组而不是 AnyObject。有什么办法可以做到这一点工作?

最佳答案

在协议(protocol)中要求 AnyObject 意味着 children 数组必须能够接受 AnyObject 条目。但听起来您希望 Bar 的子对象只是 Foo 对象。

相反,您可以给协议(protocol)一个 associated type :

protocol Parent {
    associatedtype Child
    var children: [Child] { get set }
}

class Foo { }

class Bar: Parent {
    var children = [Foo]()
    init() {}
}

关于swift - 我的类可以覆盖 Swift 中的协议(protocol)属性类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31765806/

相关文章:

swift - 连接到 Pusher ChatKit [Swift]

ios - 如何使用 URL Swift 3 下载图像?

使用 kvo 的快速协议(protocol)扩展

objective-c - Objective C 中的协议(protocol)继承

ios - 让 Swift 类同时充当 UIViewController 子类和 UITableViewDelegate

http - HTTP协议(protocol)使用哪种编码?

ios - 从 Block 获取 WebService 响应到 WatchKit App

ios - 为什么当 ActiveReferenceCount > 0 时对象被取消初始化

swift - Set 如何解决哈希冲突?

swift - 需要帮助理解 Swift 中的 GeneratorOf 和 SequenceOf