← Back to Swift Course | Chapter 9: Inheritance & Protocols | Lesson 1 of 7

Inheritance

Inheritance lets one class be built as a special version of another class, automatically getting all its properties and abilities.

Basic Class Inheritance

Writing class Dog: Animal makes Dog a subclass of Animal, automatically inheriting all of its properties and methods.

Example: Basic Class Inheritance

markup
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: "Rex")
print(dog.describe())

Adding New Members in a Subclass

A subclass can introduce entirely new properties and methods in addition to everything it inherits.

Example: Adding New Members in a Subclass

markup
class Animal {
    var name: String
    init(name: String) {
        self.name = name
    }
}
class Dog: Animal {
    func bark() -> String {
        return "\(name) says Woof!"
    }
}
let dog = Dog(name: "Rex")
print(dog.bark())
Common Mistakes
  1. Forgetting only classes support inheritance in Swift; structs and enums cannot inherit from another struct or enum.
  2. Trying to inherit from more than one class at once; Swift only allows single inheritance for classes (unlike protocols, which support multiple conformance).
  3. Forgetting final prevents a class from being subclassed at all, which is useful for performance and API design.
Chapter Summary
  • A subclass inherits properties and methods from its superclass using class Sub: Super.
  • Swift classes support only single inheritance -- one direct superclass.
  • final on a class prevents any further subclassing.
  • A subclass can add new properties and methods beyond what it inherited.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.