Last active
December 18, 2018 15:24
-
-
Save gabrielepalma/4cb4e8baaebf5368b2ea0c8a91c3b399 to your computer and use it in GitHub Desktop.
Static/dynamic dispatch
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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