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:
- Protocol requirements use dynamic dispatch.
- 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 keep up with the new content. There I write daily on iOS development, programming, and Swift.