-
-
Save Oni-zerone/db30fcd8c46ea932ba2322a5d461ffbc to your computer and use it in GitHub Desktop.
Static/dynamic dispatch
This file contains 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 { | |
var animalType: String { | |
return "dog" | |
} | |
} | |
protocol Animal { | |
var animalType: String { get } | |
} | |
extension Animal { | |
var animalType: String { | |
return "animal" | |
} | |
func eat() { | |
print("\(animalType) eats") | |
} | |
func talk() { | |
print("\(animalType) 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