Subclass always picks its superclass's associatedtype

Minified example:

protocol P { associatedtype A }

class C: P { typealias A = Int }

class D: C { typealias A = String }

extension P {
  static func printA() { print(A.self) }
}

D.printA()      // Int
print(D.A.self) // String

This behavior occurs because D’s conformance to P is inherited from C.

The only way in which D can customize the conformance, is by overriding methods from C that satisfy requirements of P. Since a typealias cannot be overridden, it follows that D cannot provide a different one for its conformance to P.

Note that the typealias in D does work when using D directly. It is just not the one used for purposes of conformance to P, since that conformance comes from C.

• • •

There are a number of other complications surrounding class and subclass conformances to protocols, especially when generics and/or existentials are involved:

SR–103 describes the inability of a subclass to override a protocol requirement for which the superclass uses a default implementation from the protocol.

The thread Need help understanding protocols and generics covers some strange edge-cases. This post by @xwu lists just about every possible combination you can imagine, and explains the behavior in all but the last one, which was discovered by @Lantua a few posts earlier.

3 Likes