Overriding Methods in Swift Protocol Extensions

Swift protocol extensions use different method dispatch rules, which often leads to a confusion.

Method dispatch refers to how a method is addressed in memory. Static dispatch means at compile time; dynamic dispatch means at runtime.

Here are the two important rules about Swift protocol extensions methods:

  1. Protocol requirements use dynamic dispatch.
  2. Protocol members use static dispatch.

You can see both at work in this example:

protocol P {
    func foo() // protocol requirement

extension P {
    func foo() { print("P.foo") }
    func bar() { print("P.bar") } // protocol member

struct A : P {
    func foo() { print("A.foo") }
    func bar() { print("A.bar") }

let a = A()
a.foo() // A.foo
a.bar() // A.bar

let p: P = A()
p.foo() // A.foo <--- dynamic dispatch
p.bar() // P.bar <--- static dispatch

The important highlight is that p uses dynamic dispatch for its method foo() and static dispatch for its method bar().

Thanks for reading!

If you enjoyed this post, be sure to follow me on Twitter to not miss any new content.

Vadim Bulavin

Creator of Yet Another Swift Blog. Senior iOS Engineer at Pluto TV. Coding for fun since 2008, for food since 2012.