Protocol variable implementing another protocol

只谈情不闲聊 提交于 2021-02-19 05:53:26

问题


I'm trying to do something like that, but then, ParentC doesn't conform to Parent because its children member isn't Child but ChildC

Which is weird because ChildC implements Child...

Is this a limit of Swift? Or is there is a way of doing that?

(I do not ask for an alternative solution, I want to know if this is possible)

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
}

回答1:


You can workaround this variance "limitation" by making Parent a protocol with associated type:

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

This will impact the places you can use Parent though, since protocols with associated types have some restrictions on where to use them.



来源:https://stackoverflow.com/questions/49554288/protocol-variable-implementing-another-protocol

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!