2

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
}
Hamish
  • 74,809
  • 18
  • 177
  • 265
Tancrede Chazallet
  • 6,845
  • 5
  • 37
  • 59

1 Answers1

2

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.

Cristik
  • 28,596
  • 24
  • 84
  • 120