TExcelTAD
Home › Swift › Swift Inheritance

Swift Inheritance

Inheritance lets one class build on another. The new class (the subclass) automatically gets the properties and methods of the existing class (the superclass), and can add new ones or replace existing behaviour. Only classes support inheritance in Swift — structs and enums do not.

Creating a subclass

Write the superclass after a colon:

swift · try it yourself
class Animal {
    let name: String
    init(name: String) { self.name = name }

    func describe() -> String {
        "\(name) is an animal"
    }
}

class Dog: Animal {
    func fetch() -> String {
        "\(name) fetches the ball"
    }
}

let rex = Dog(name: "Rex")
print(rex.describe())   // inherited
print(rex.fetch())      // new in Dog
Rex is an animal
Rex fetches the ball

Dog declared no initializer, so it inherits init(name:) from Animal.

Overriding methods and properties

To replace an inherited member, write override in front of it. The keyword is mandatory: it prevents accidental overrides and catches typos (the compiler complains if nothing matches). Use super to call the superclass version.

swift · try it yourself
class Animal {
    let name: String
    init(name: String) { self.name = name }

    var sound: String { "..." }

    func speak() -> String {
        "\(name) says \(sound)"
    }
}

class Cat: Animal {
    override var sound: String { "Meow" }
}

class Parrot: Animal {
    override var sound: String { "Hello!" }

    override func speak() -> String {
        super.speak() + " (twice) " + sound
    }
}

let animals: [Animal] = [Animal(name: "Blob"), Cat(name: "Mimi"), Parrot(name: "Kiwi")]
for a in animals {
    print(a.speak())
}
Blob says ...
Mimi says Meow
Kiwi says Hello! (twice) Hello!

The array has type [Animal], yet each element runs its own version of speak() and sound. This is polymorphism: the method that runs is chosen by the object's real type at runtime.

Subclass initializers

A subclass that adds stored properties needs its own initializer. It sets the new properties, then calls super.init:

swift · try it yourself
class Employee {
    let name: String
    var salary: Double

    init(name: String, salary: Double) {
        self.name = name
        self.salary = salary
    }

    func monthlyPay() -> Double { salary / 12 }
}

class Manager: Employee {
    var bonus: Double

    init(name: String, salary: Double, bonus: Double) {
        self.bonus = bonus
        super.init(name: name, salary: salary)
    }

    override func monthlyPay() -> Double {
        super.monthlyPay() + bonus / 12
    }
}

let staff = [Employee(name: "An", salary: 48000),
             Manager(name: "Bao", salary: 60000, bonus: 12000)]
for person in staff {
    print(person.name, person.monthlyPay())
}
An 4000.0
Bao 6000.0

Checking and casting types

Use is to test a type and as? to try a downcast (the result is optional). as! forces the cast and crashes if it is wrong, so prefer as?.

swift · try it yourself
class Shape {}
class Circle: Shape { let radius = 2.0 }
class Square: Shape { let side = 3.0 }

let shapes: [Shape] = [Circle(), Square(), Circle()]

let circleCount = shapes.filter { $0 is Circle }.count
print("Circles:", circleCount)

for shape in shapes {
    if let c = shape as? Circle {
        print("circle with radius", c.radius)
    } else if let s = shape as? Square {
        print("square with side", s.side)
    }
}
Circles: 2
circle with radius 2.0
square with side 3.0
circle with radius 2.0

Preventing overrides with final

Mark a method, property or the whole class final to forbid overriding or subclassing:

swift · try it yourself
final class Config {
    let debug = false
}

class SpecialConfig: Config {}
error: emit-module command failed with exit code 1 (use -v to see invocation)
<source>:5:7: error: inheritance from a final class 'Config'
3 | }
4 |
5 | class SpecialConfig: Config {}
  |       `- error: inheritance from a final class 'Config'

Inheritance vocabulary

Term Meaning
Superclass / base class The class being inherited from
Subclass The class that inherits (class Dog: Animal)
override Replaces an inherited method, property or initializer
super Accesses the superclass implementation
final Forbids further overriding or subclassing
Upcast Treating a Dog as an Animal (always safe, automatic)
Downcast as? / as! from Animal back to Dog

Tip: Swift classes can inherit from only one superclass. For sharing behaviour across unrelated types, Swift developers usually prefer protocols — the next big topic — over deep class hierarchies.

Test yourself

Which keyword is required when a subclass replaces a superclass method?

  1. super
  2. override
  3. final
  4. virtual

What does shape as? Circle return if shape is actually a Square?

  1. A crash
  2. nil
  3. An empty Circle
  4. The Square unchanged

Which types can use inheritance in Swift?

  1. Structs and classes
  2. Only classes
  3. Classes and enums
  4. All types