Tools
Log in
English

Learn to codeSwift

Swift inheritance

Based on Swift 6.4

Swift class inheritance with override, super, final and two-phase init.

In one line

Building a new class (the child) on top of an existing one (the parent), keeping its properties and methods and changing only what you need with override. In Swift only classes inherit.

Why you need it

Write walks, runs and hill runs as unrelated types and the title, minutes and summary code appears three times. Changing the summary means three edits.

Keep the shared part in Workout once, and give each child only what differs (distance, climb) and its own calculation. Change the summary once in the parent and every workout follows.

Everyday picture

Think of a basic recipe and its variations. Kimchi fried rice inherits the basic fried rice recipe and rewrites one step, "fry the kimchi first", following the rest as written. The last variation may carry a note saying "no more changes" (final).

Example code

main.swift · 57 lines
let walk = Workout(title: "Walk", minutes: 40)let run = Run(minutes: 30, km: 6)let hill = HillRun(minutes: 30, km: 5, climb: 150)for w in [walk, run, hill] {    print(w.report())} class Workout {    let title: String    let minutes: Int     init(title: String, minutes: Int) {        self.title = title        self.minutes = minutes    }     func calories() -> Int {        let kcal = minutes * 4        return kcal    }     func report() -> String {        "\(title) \(minutes) min, \(calories()) kcal"    }} class Run: Workout {    let km: Int     init(title: String = "Run", minutes: Int, km: Int) {        self.km = km        super.init(title: title, minutes: minutes)    }     override func calories() -> Int {        let kcal = km * 60        return kcal    }     override func report() -> String {        super.report() + ", \(km) km"    }} final class HillRun: Run {    let climb: Int     init(minutes: Int, km: Int, climb: Int) {        self.climb = climb        super.init(title: "Hill run", minutes: minutes, km: km)    }     override func calories() -> Int {        let extra = climb / 2        return super.calories() + extra    }}

When to use it

  • Classes fit the sentence "X is a kind of Y" (a run is a kind of workout)
  • You reuse almost all of the parent and change one or two things (override plus super)
  • Close classes that must not be extended with final; the compiler can also make calls faster.

Structs and enums have no inheritance. To make several types do the same job, use the protocols in the next topics.

An init reaches its parent with super.init(...); a method reaches the parent version with super.method().

Common mistakes

Calling super.init first

The order is the opposite of Java. In Swift the child must set all of its own properties before calling the parent init, so the child is never half-empty even if the parent calls an overridden method.

Wrong

let swim = Swim(minutes: 20, laps: 8)print(swim.laps) class Exercise {    let minutes: Int     init(minutes: Int) {        self.minutes = minutes    }} class Swim: Exercise {    let laps: Int     init(minutes: Int, laps: Int) {        super.init(minutes: minutes)        self.laps = laps    }}

What the Swift compiler sayserror: property 'self.laps' not initialized at super.init call

Fixed

let swim = Swim(minutes: 20, laps: 8)print(swim.laps) class Exercise {    let minutes: Int     init(minutes: Int) {        self.minutes = minutes    }} class Swim: Exercise {    let laps: Int     init(minutes: Int, laps: Int) {        self.laps = laps        super.init(minutes: minutes)    }}

When you run it8

Forgetting override

When the parent already has a method with that name, you must write override. The compiler stops you from replacing parent behavior by accident. Writing override on a method the parent does not have is also an error.

Wrong

let yoga = Yoga(title: "Yoga", minutes: 30)print(yoga.report()) class Yoga: Workout {    func calories() -> Int {        minutes * 3    }}

What the Swift compiler sayserror: overriding declaration requires an 'override' keyword

Fixed

let yoga = Yoga(title: "Yoga", minutes: 30)print(yoga.report()) class Yoga: Workout {    override func calories() -> Int {        minutes * 3    }}

When you run itYoga 30 min, 90 kcal

Inheriting from a final class

final class means the line ends here. Put it on classes whose rules would break if extended. If you must inherit, branch off a parent that is not final (Run). A child with no new properties inherits the parent initializers as they are.

Wrong

class TrailRun: HillRun {}

What the Swift compiler sayserror: inheritance from a final class 'HillRun'

Fixed

print(TrailRun(minutes: 10, km: 2).report()) class TrailRun: Run {}

When you run itRun 10 min, 120 kcal, 2 km

Check yourself

Question 1

The variable type is Workout, but the object is a Run. What is printed?

let w: Workout = Run(minutes: 10, km: 2)print(w.calories())

Show the answer

Answer: 2. 120 An overridden method is chosen by the real object, not the variable type: the Run rule gives 2 × 60 = 120.

Question 2

Can a struct inherit from a class?

struct Stretch: Workout {}

Show the answer

Answer: 2. A compile error Only classes inherit. Structs and enums can list only protocols after the colon, so naming a class is a compile error.

Questions people ask

Can a struct inherit?

No. Only classes inherit. To share behavior among structs and enums, use protocols and extensions.

When does a child init call super.init?

After the child has set every property it added, the opposite order to Java. Once the parent init returns, you may change inherited properties and call methods.

Why mark something final?

To close classes and methods whose rules would break if subclassed or overridden. Since nothing can override them, the compiler can also choose faster calls.