问题
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