Skip to content
Tutorials Center
My learning

Topics

Lesson 48 of 146 ยท Structures, Classes and Enums

Inheritance

Learn Swift class inheritance - subclassing, override, super, final, polymorphism and dynamic dispatch, overriding properties, and why composition and protocols are often a better choice.

Inheritance lets one class build on another. A Dog class can start from everything an Animal already has (properties, methods, initializers) and then add or change only what is different. The class you build on is the superclass; the new one is the subclass.

Only classes support inheritance in Swift. Structs and enums cannot be subclassed; they share behavior through protocols instead (see Protocols). That is a deliberate design decision, and by the end of this lesson you will see both what inheritance is good for and why modern Swift reaches for it less often than Java or C++ code does.

Your first subclass

Write the superclass name after a colon. The subclass inherits all its properties and methods.

Swift A subclass inherits everything

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Bicycle never declared speed or describe(), yet it has both. It also adds hasBasket, which a plain Vehicle does not have. A subclass can itself be subclassed, forming a chain; a class that has no superclass is called a base class.

Overriding methods

A subclass can replace an inherited method with its own version. You must write the keyword override, so you never replace something by accident (and so the compiler can warn you when the superclass changes).

Swift override and super

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

super.describe() calls the superclass version. You can extend the parent's behavior (as here), completely replace it (leave super out), or call it first or last depending on what makes sense.

Forgetting override

If you declare a method with the same name and signature as an inherited one and leave out override, Swift stops you.

Swift Missing override (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The message is overriding declaration requires an 'override' keyword. The reverse mistake is also caught: writing override on a method that does not exist in the superclass gives method does not override any method from its superclass, which usually points to a typo.

Polymorphism

Because a Cat is an Animal, you can store cats, dogs and plain animals in one array of Animal and call the same method on each. At run time Swift picks the version that belongs to the object's actual class. This is called polymorphism (many forms) or dynamic dispatch.

Swift One array, many behaviors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

speak() is written once in Animal, but it calls sound(), and each object answers in its own way. You can add new animals without touching the loop. This is the main benefit of inheritance: shared code plus customization.

Upcasting and downcasting

Assigning a Dog to an Animal variable is always safe (an upcast). Going the other way requires a check, using as? or is; see Type Casting.

Swift Checking the actual class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Overriding properties

You can override inherited properties, too, but only to provide a custom getter and setter or to add observers; you cannot change whether a property is stored. A read-only property may become read-write, but never the reverse.

Swift Overriding properties and observers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Inside a subclass, super.name gives access to the parent's version of a computed property. See Properties for the observer rules.

Preventing inheritance with final

By default any class can be subclassed and any method overridden. Mark a class, method or property final to forbid it.

Swift Subclassing a final class (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The compiler says inheritance from a final class 'Config'. Why bother? Design and speed. A final class tells readers "nobody overrides this", and lets the compiler call its methods directly (static dispatch) instead of looking them up in a table at run time. Many Swift developers make classes final by default and remove the keyword only when they actually need subclassing. Outside the module, public classes are not subclassable unless declared open; see Access Control.

Initializers in subclasses

A subclass with new stored properties must initialize its own properties first and then call super.init. This two-phase rule is explained fully in Initializers; here is the short form with an override:

Swift super.init and override init

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Abstract classes: not in Swift

Swift has no abstract keyword. If a base class has a method that every subclass must implement, there are two honest options. Use fatalError("Subclass must override") in the base method, which is a run-time crash if someone forgets. Or, better, declare a protocol so the compiler enforces the requirement.

Swift A protocol instead of an abstract class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Here Circle and Square are structs, so there is no shared base state to worry about, and forgetting draw() is a compile error rather than a crash. This is why Swift developers often say "prefer protocols and composition over inheritance".

When to use inheritance

Use it when:

  • there is a genuine is-a relationship and shared stored state;
  • a framework gives you a base class to extend (UI view controllers, test cases);
  • you need reference semantics plus customizable behavior.

Avoid it when:

  • you only want to share a few functions (use protocol extensions or a helper type);
  • the hierarchy has more than two or three levels, which becomes hard to follow;
  • the subclass has to disable inherited behavior, a sign the relationship is wrong.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the override keyword do?

    override is required to replace an inherited member, and the compiler reports an error if there is nothing to override.
  2. 2. An array of type [Animal] holds subclass objects that override sound(). Which version runs when you call sound() on each element?

    That is polymorphism: the method is chosen at run time from the object's real class, not the variable's declared type.
  3. 3. Which keyword stops a class from being subclassed?

    A final class cannot be subclassed. final on a method or property blocks overriding.
  4. 4. Can a struct inherit from another struct?

    Inheritance is a class-only feature in Swift.
  5. 5. How do you call the superclass's version of an overridden method?

    super refers to the superclass; super.describe() runs the inherited implementation.

Summary

  • A subclass (class Dog: Animal) inherits properties, methods and initializers; only classes can inherit.
  • Replace members with override; call the parent with super.
  • Polymorphism lets code written against the superclass use each object's own override.
  • You can override properties with custom getters, setters or observers, but not change them from stored to computed or vice versa.
  • final forbids subclassing or overriding and enables faster direct calls.
  • Swift has no abstract classes; protocols give compile-time enforcement.
  • Prefer shallow hierarchies, composition and protocols.

Next: Access Control