Swift Protocol Extensions Method Dispatch

https://www.sketchport.com/drawing/5319150117322752/liar-the-sorcerer-troll

What did I learn?

  1. Protocol extensions have 2 types of methods. Requirement methods and Static methods (“Not Backed by Requirement”).
  2. Requirement methods use dynamic dispatch. Static methods use static dispatch.
  3. It is really important to know the difference so you don’t create bugs.

A Bug hidden among heroes

protocol Fighter{
func fight() //Requirement
}
extension Fighter{
//Requirement
func fight(){
self.punch()
}
//Static method (it is not required in the protocol)
func punch(){
print("Fighter punch")
}
}
protocol MagicalFighter : Fighter{
func castSpell() //Requirement
}
extension MagicalFighter{ //Requirement
func castSpell(){
print("MagicalFighter casted a spell")
}
//Static
func punch(){
self.castSpell()
print("Magical fighter punch")
}
}
struct Hero : MagicalFighter{
func castSpell(){
print("Hero casted special spell")
}
}
let gordo = Hero()
gordo.fight()

What gets printed and why?

Method Dispatch

Dynamic Dispatch.

Static Dispatch

Requirement methods

Static methods

So, what does it all mean?

Going back to the example

Final words

Playground

References:

--

--

--

Software Engineer, coding since 2001. I have done plenty of work in iOS with Objective-C and Swift.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

The Deprecated Genie

Agile Transformation —going towards Business Agility

Debug more effectively with Pry

medical director of the Brigham and Women’s Hospital Heart and Vascular Center

How to clear Tableau Desktop Certified Associate Exam : Tips & Alerts

Dear Software Development Companies… You need to do better.

Working with Json Data and function PostgreSQL

Setting Breakpoints and Exception Hooks in Python

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Leandro Pérez

Leandro Pérez

Software Engineer, coding since 2001. I have done plenty of work in iOS with Objective-C and Swift.

More from Medium

MVVM-C Xcode Template to reduce development time

Design an APP Routing(updating. . .)

How to run a App on iOS simulator without open Xcode

Swift: easy way to add tap gesture on a View