Class Inheritance in Swift
Level 4382 keystrokes
Dog and Cat inherit from Animal and override speak(). An [Animal] array holds both, and calling speak() on each element runs the subclass version (dynamic dispatch): Rex: Woof! and Whiskers: Meow!.
Swift code
// Base class with a name and a default speak()1class Animal {2 var name: String3 init(name: String) { self.name = name } // Default implementation, returns "..."4 func speak() -> String { return "..." }5}6 7class Dog: Animal { // Dog replaces speak() with its own version8 override func speak() -> String { return "Woof!" }9}10 11class Cat: Animal { // Cat does the same with a different result12 override func speak() -> String { return "Meow!" }13}14 // Both subclasses fit in an array typed with the base class15let pets: [Animal] = [Dog(name: "Rex"), Cat(name: "Whiskers")]// speak() is chosen at run time by the actual class: Rex: Woof!, Whiskers: Meow!16for pet in pets { print("\(pet.name): \(pet.speak())") }Output
Rex: Woof! Whiskers: Meow!
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this Swift code and how often they appear.
"× 12(× 10)× 10:× 8{× 8}× 8.× 6-× 3>× 3!× 2