Should allow covariance of {get}-only protocol property requirements?

This came up for us today -- in a situation like this:

class Super {}
class Sub : Super {}
protocol P {
    var property: Super {get}
}
struct S : P {
    var property: Sub
}

Currently Swift will error that Type 'S' does not conform to protocol 'P' because the property type is not an exact match. When the protocol only requires {get}, though, it ought to be safe to allow for covariance in the witness, shouldn't it?

In theory, yes (SR-522). In practice, that might result in a dangerous number of behavior changes, where things that previously weren't considered valid witnesses might now be considered a better match.

3 Likes

Thanks for the bug pointer! I did a search and failed to find it.

1 Like

I've run into the same issue a few times, but it's possible to work around it by using an associatedtype:

class Super {}
class Sub: Super {}
protocol P {
  associatedtype S: Super
  var property: S { get }
}
struct S: P {
  var property: Sub
}
4 Likes

Is the danger @jrose mentioned still inherent in this implementation? I don’t know, because I didn’t understand it in the first place.

Terms of Service

Privacy Policy

Cookie Policy