Protocol property requirements do not support subtyping?

Basically, the following code does not compile:

protocol Proto {
    var a: A {get}
}

class A {}

class B: A {}

class C: Proto {
    let a = B()
}

with messages:

error: type 'C' does not conform to protocol 'Proto'
class C: Proto {
      ^
/Users/wtedst/Test.swift:10:9: note: candidate has non-matching type 'B'
    let a = B()
        ^
/Users/wtedst/Test.swift:2:9: note: protocol requires property 'a' with type 'A'; do you want to add a stub?
    var a: A {get}
        ^

am I missing something? I've done a quick search through recent bug reports and commits to the master branch and haven't found anything relevant :woozy_face:.

Protocol Witness Matching Mini-Manifesto discusses this, it’s not currently supported but may be eventually

2 Likes

@suyashsrijan The manifesto has been written before Swift declared ABI stability; is it ABI-breaking now if one would implement this?

I am actually not sure if allowing subtyping could break ABI, but I am aware that it could cause some other breakage (by changing behaviour of existing code in subtle ways, etc). If you search for this functionality on the bug tracker, you'll find some bugs with discussions around it.

In the meantime, you can do something like:

protocol Foo {
  associatedtype T: A
  var someProperty: T { get }
}

class A {}
class B: A {}

class C: Foo {
  let someProperty = B()
}

let foo: some Foo = C()
1 Like

I've just opted for a computed property of the exact supertype instead of using an associated type β€” I only needed the base class. Thanks anyways! It just never occurred to me that such behavior was actually unsupported.