Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift protocol conformance with associated type using same-type constraint

Tags:

swift

swift4

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
}
like image 306
Werner Altewischer Avatar asked Nov 02 '25 18:11

Werner Altewischer


1 Answers

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  {
}
like image 105
Puneet Sharma Avatar answered Nov 04 '25 13:11

Puneet Sharma