Alexito's World

A world of coding 💻, by Alejandro Martinez

Understanding Swift Protocol Extensions dispatching

As I said on my Fist impressions on WWDC 2015 I was really excited for finally having traits in Swift, in form of Protocol extensions. After playing with them this days I most than happy :) But I’ve seen some people struggling to understand how the dispatching of the methods works, in other words, which method will be called?

To understand it you can think in this two cases:

  1. If you are dealing with a specific type (class, struct...): it will always use the methods implemented on that type.
  2. If you are dealing with a protocol: it will use the methods declared in the real type if they are declared in the protocol, if not it will use always the methods on the protocol extension.

I’m gonna use the example that Mike Ash uses in his post (Friday Q&A 2015-06-19: The Best of What's New in Swift, go read it!)

Declare a protocol P that doesn’t declare the func b()

protocol P {
  func a()

Extend the protocol to give default implementations of the methods, including the new func b().

extension P {
  func a() {
      print("default implementation of A")

  func b() {
      print("default implementation of B")

Define a struct S that derives from P, and reimplements a() and b().

struct S: P {
  func a() {
      print("specialized implementation of A")

  func b() {
      print("specialized implementation of B")

Now if you have a variable declared as P

let p: P = S()
p.a() // specialized, because it's defined in the protocol
p.b() // default, because it's added by the extension

But if you have the variable declared as S

let p2 = S()
p2.a() // specialized
p2.b() // specialized

At the beginning it may be a little confusing, but once you start using it it seems natural (unless I’m not understanding it at all :P).

You can Download the Playground which contains more examples. For any feedback you can reach me on Twitter.

If you liked this article please consider supporting me