๐ŸŽ“ A1Learner
๐Ÿ”

Swift Inheritance

Inheritance lets a subclass take the properties and methods of a parent class. The subclass can add its own parts and replace a parent method with its own version.

Using what the parent gives

Dog adds nothing to Animal in this program. The dog still reads the parent name property and calls the parent describe method.

class Animal {
    var name: String
    init(name: String) {
        self.name = name
    }
    func describe() -> String {
        return "\(name) is an animal"
    }
}
class Dog: Animal {
}
let dog = Dog(name: "Pip")
print(dog.name)
print(dog.describe())

Replacing a method with override

Animal gives three dots as its sound, and Dog replaces that method with its own version. Each instance prints the sound of its own class.

class Animal {
    func sound() -> String {
        return "..."
    }
}
class Dog: Animal {
    override func sound() -> String {
        return "Woof"
    }
}
let animal = Animal()
print(animal.sound())
let dog = Dog()
print(dog.sound())

Extending the parent version with super

The Dog version of describe starts from the parent text through super. It then adds its own ending to that text.

class Animal {
    func describe() -> String {
        return "An animal"
    }
}
class Dog: Animal {
    override func describe() -> String {
        return super.describe() + " that barks"
    }
}
let dog = Dog()
print(dog.describe())

Example

class Vehicle {
    var wheels: Int
    init(wheels: Int) {
        self.wheels = wheels
    }
    func sound() -> String {
        return "..."
    }
    func describe() -> String {
        return "\(wheels) wheels"
    }
}
class Car: Vehicle {
    override func sound() -> String {
        return "Vroom"
    }
}
let car = Car(wheels: 4)
print(car.describe())
print(car.sound())
print(car.wheels)

Key points

  • A subclass takes the properties and methods of its parent class.
  • The subclass name is followed by a colon and the parent class name.
  • An inherited method can be used with no change at all.
  • The override mark replaces a parent method with the subclass version.
  • The word super calls the parent version of a method from inside the subclass.
  • A subclass also inherits the init of its parent when it adds no stored properties of its own.

In this example, the Car class inherits from Vehicle, so the car is built with the parent init and holds 4 wheels. The describe call uses the parent method unchanged and prints 4 wheels. The sound call uses the Car override and prints Vroom, and the last print reads the inherited wheels property.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz Swift Compiler

Exercise

What does the override mark do in a subclass?