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
  • 78,605
  • 19
  • 187
  • 280
Tancrede Chazallet
  • 7,035
  • 6
  • 41
  • 62

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
  • 30,989
  • 25
  • 91
  • 127