我正在尝试做类似的事情,但是,ParentC
不符合Parent
因为它是children
会员不是Child
but ChildC
这很奇怪,因为ChildC
实施Child
...
这是 Swift 的限制吗?或者有办法做到这一点吗?
(我不要求替代解决方案,我想知道是否this是可能的)
protocol Parent: Codable {
var children: [Child] { get }
}
protocol Child: Codable {
var name: String { get }
}
struct ParentC: Parent {
var children: [ChildC]
}
struct ChildC: Child {
var name: String
}
您可以通过以下方式解决此差异“限制”Parent
具有关联类型的协议:
protocol Parent: Codable {
associatedtype ChildType: Child
var children: [ChildType] { get }
}
这将影响您可以使用的地方Parent
不过,由于具有关联类型的协议对使用它们的位置有一些限制。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)