Update – Protocol Extensions and Polymorphism

I wrote in August of last year about some potential confusion coming out of the decision to statically dispatch calls to methods defined in a protocol extension that were not defined in the protocol itself. (Whereas calls to methods defined in the protocol are always dynamically dispatched.) This allowed the protocol / extension designer to differentiate between customization points (methods defined in the protocol) and non-customizable code (methods not defined in the protocol, but implemented in an extension).

It looks like Apple’s received some feedback around this, and Doug Gregor acknowledges this is his “Completing Generics” Manifesto. (Update May 5: Austin Zheng has created a formatted version of the manifesto, available on GitHub.) However I’m not optimistic that this will get changed in future versions of Swift, as he puts it in his “Maybe” section:

Maybe

There are a number of features that get discussed from time-to-time, while they could fit into Swift’s generics system, it’s not clear that they belong in Swift at all. The important question for any feature in this category is not “can it be done” or “are there cool things we can express”, but “how can everyday Swift developers benefit from the addition of such a feature?”. Without strong motivating examples, none of these “maybes” will move further along.

Dynamic dispatch for members of protocol extensions

Only the requirements of protocols currently use dynamic dispatch, which can lead
to surprises:

protocol P {
  func foo()
}
extension P {
  func foo() { print(“P.foo()”)
  func bar() { print(“P.bar()”)
}
struct X : P {
  func foo() { print(“X.foo()”)
  func bar() { print(“X.bar()”)
}
let x = X()
x.foo() // X.foo()
x.bar() // X.bar()
let p: P = X()
p.foo() // X.foo()
p.bar() // P.bar()

Swift could adopt a model where members of protocol extensions are dynamically dispatched.

Fingers crossed, but I think the ship has probably sailed on this – I wonder if the change of behaviour would result in more confusing bugs than this quirk of the language did in the first place.


Leave a Reply

Your email address will not be published. Required fields are marked *