4

I'm trying to define a protocol B which extends protocol A (the latter containing the associated type C), while using a where clause with same-type constraint as the compiler suggests. However, when doing this the code won't compile anymore. Is this a Swift bug (Swift 4 in this case)?

To be more concrete, the code below does not compile with error:

type 'E' does not conform to protocol 'A'

class D {

}

protocol A: class {
    associatedtype C: AnyObject
}

protocol B: A where C == D {

}

class E: B {

}

Changing the definition of protocol B as specified below will compile but will show this warning instead:

Typealias overriding associated type 'C' from protocol 'A' is better expressed as same-type constraint on the protocol

protocol B: A {
    typealias C = D
}

The only way to make it compile without warnings is to specify the typealias in class E and using the where clause in protocol B, but this seems to duplicate the typealias unnecessary:

protocol B: A where C == D {

}

class E: B {
    typealias C = D
}

1 Answer 1

3

I guess same type constraint on protocol declaration is not getting read by classes when it conforms to that protocol.

To avoid reduplication of typealias, you can remove same type constraint from protocol B and use extension to give typealias on protocol B.

class D {

}

protocol A: class {
    associatedtype C
}

protocol B: A  {
}

extension B {
    typealias C = D
}

class E: B  {
}
2
  • 1
    Thanks! This work around does seem to fix it. However, I still consider it a bug and filed an issue in the Swift issue tracker. Dec 19, 2017 at 19:16
  • Do you know if this bug was prioritized or fixed? I think I'm facing the same issue. Oct 10, 2018 at 12:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.