Skip to content

Instantly share code, notes, and snippets.

@gabrielepalma
Last active December 18, 2018 15:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save gabrielepalma/4cb4e8baaebf5368b2ea0c8a91c3b399 to your computer and use it in GitHub Desktop.
Save gabrielepalma/4cb4e8baaebf5368b2ea0c8a91c3b399 to your computer and use it in GitHub Desktop.
Static/dynamic dispatch
struct Dog : Animal {
func eat() {
print("dog eats")
}
func talk() {
print("dog talk")
}
}
protocol Animal {
func talk()
}
extension Animal {
func eat() {
print("animal eats")
}
func talk() {
print("animal talk")
}
}
func animalDoAnimalStuff(animal : Animal) {
animal.eat()
// eat is defined in extension, thus it is statically dispatched and will print "animal eats"
animal.talk()
// talk is declared in the protocol, thus it is dynamically dispatched and will print "dog talk"
}
let dog = Dog()
animalDoAnimalStuff(animal: dog)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment