2

It's hard for me to give a good title to the question, but here is my case:

protocol A: class {}

protocol B: A {}

protocol C {
    var P: A { get set }
}

class D: C {
    var P: B
}

The error that I get is:

Type ‘D’ does not conform to protocol ‘C’

Basically, from my understanding, this error should not happen because protocol B implements protocol A, which means that class D actually does conform to protocol C. I guess the compiler cannot infer that and I need to guide it through that. Can anyone explain to me how I can do that?

I appreciate the help, thank you.

Guy Daher
  • 5,526
  • 5
  • 42
  • 67
  • Protocol C has a variable P of type A. Class D has a variable B of type B. Yes, B is a subclass of A, but B is a different type than A so therefore D does not implement protocol C – Paulw11 Apr 06 '17 at 12:03
  • 1
    You cannot implement implement the protocol requirement `var P: A { get set }` with `var P: B`. If this were possible, and you upcast an instance of `D` to `C`, then you'd be able to assign *anything* that conforms to `A` to a property of type `B` – which would be madness. For this reason, read-write properties have to be invariant. – Hamish Apr 06 '17 at 12:08

0 Answers0