Class Inheritance in Swift

Level 4222 keystrokes

Dog inherits name and the initializer from Animal and overrides speak. Calling speak on a Dog runs the overridden version, which prints Buddy says Woof!.

Swift code

// Base class
1class Animal {
2 var name: String
// Initializer that sets name
3 init(name: String) { self.name = name }
// Default behavior that subclasses can replace
4 func speak() { print("...") }
5}
6
// Dog inherits from Animal, including name and init(name:)
7class Dog: Animal {
// override is required to replace the superclass method
8 override func speak() {
// Uses the inherited name property
9 print("\(name) says Woof!")
10 }
11}
12
// Uses the initializer inherited from Animal
13let dog = Dog(name: "Buddy")
// Runs Dog's version: Buddy says Woof!
14dog.speak()

Output

Buddy says Woof!
Practice typing this code

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.

  • (× 8
  • )× 8
  • "× 6
  • .× 5
  • {× 5
  • }× 5
  • :× 4
  • =× 2
  • !× 1
  • \× 1

More Swift examples at level 4

← Swift typing practice