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/