skip to content

Subclassing and Overrides

Classes inherit and override with override and super, and final stops both. Interviewers ask when inheritance is the wrong tool in Swift and what composition with protocols offers instead.

on this pageshow

explore

questions

5

In Swift, how does a subclass replace an inherited method with `override`, and how does it reach the superclass version through `super`?

level: juniorimportance: must knowfreq 72%

answer

  1. one superclass, classes only
  2. keyword checked in both directions
  3. missing keyword vs no match
  4. super.method() inside the override

basics

~20 s

A Swift subclass marks a replacement method, property or subscript with override. The compiler rejects a missing override and also an override that matches nothing. Inside it, super.method() calls the superclass implementation, which Swift never forces you to call.

solid answer

~40 s

A Swift class inherits from at most one superclass. Structs, enums and actors cannot inherit, and there is no universal base class. To replace an inherited method, property or subscript you write `override`, and the compiler checks it both ways. Leaving it off is "overriding declaration requires an 'override' keyword". Writing it on something with no superclass match, such as a typo or different labels, is "method does not override any method from its superclass". Inside the override, `super.headers()`, `super.someProperty` or `super[i]` reaches the superclass implementation, so you can extend it instead of replacing it. A call through a variable typed as the superclass still runs the subclass's version. Nothing forces a method override to call `super`, so a base class that needs that call has to document it.

code

swift · 19 lines
swift
class APIService {
    func headers() -> [String: String] {
        ["Accept": "application/json"]
    }
    func describe() -> String { "generic backend" }
}

class BillingService: APIService {
    override func headers() -> [String: String] {
        var result = super.headers()          // start from the superclass version
        result["X-Billing-Version"] = "3"
        return result
    }
    override func describe() -> String { "billing backend" }
}

let service: APIService = BillingService()
print(service.describe())                    // billing backend
print(service.headers().keys.sorted())       // ["Accept", "X-Billing-Version"]

go deeper

for a junior

Recall that only classes inherit, one superclass each, and that override is a required keyword. Be able to write super.method() inside an override.

for a middle

Explain both compiler checks, missing override and override with no match, and why each one catches a different accident. Note that calling super is optional for methods.

for a senior

Show that an unforced super call is a hidden contract. When a base class relies on subclasses calling through, the dependency lives only in docs and review, so design to avoid it.

for a principal

Use the required override keyword as a reason for keeping inheritance shallow. Every override is a promise about base-class internals, and Swift checks the signature but never the behaviour.

## Single inheritance, and only for classes In Swift, **inheritance** is a class feature. A class names at most one **superclass**, written first after the colon (`class BillingService: APIService, CustomStringConvertible`); any names after it are protocols. Several facts follow from the declaration rules: - **No universal base class.** A class written without a superclass is a *base class*. It does not silently inherit from `NSObject` or any other root; that only happens when you write it, which is Objective-C interop material. - **One superclass only.** Listing two classes is rejected with "multiple inheritance from classes 'Base' and 'Sub'". - **Value types cannot inherit.** A struct or enum that names a class in its inheritance clause gets "inheritance from non-protocol type 'Base'". Structs and enums share behaviour through protocols instead. - **Actors cannot inherit either**: the Swift 6.4 compiler reports "actor types do not support inheritance". A subclass inherits the superclass's methods, properties and subscripts. Designated initializers are inherited only under the automatic-initializer-inheritance rules, which belong to the lesson on initializers. ## `override` is mandatory, and the compiler checks it To give a subclass its own version of an inherited **instance method, type method (`class func`), instance or type property, or subscript**, you prefix the declaration with `override`. A designated initializer that matches a superclass designated initializer is marked `override` too. The keyword is not documentation; the compiler enforces it in both directions: | What you write | What Swift 6.4 says | |---|---| | Redeclare an inherited method without `override` | error: overriding declaration requires an 'override' keyword | | `override` on a method with no matching superclass method (a typo, other labels) | error: method does not override any method from its superclass | | `override` on a struct member | error: 'override' can only be specified on class members | | `override` of a `final` method | error: instance method overrides a 'final' instance method | The first check stops **accidental overrides**: a new method that happens to share a name with an inherited one cannot quietly replace it. The second stops **accidental non-overrides**: a misspelled `describ()` that the author believed was an override is an error rather than a new, unused method. The check walks the whole chain, so `override` matches a declaration in the superclass or any of its ancestors. For a property override you state both the name and the type, so the compiler can match it. ## Reaching the superclass with `super` Inside an override, the `super` prefix reaches the superclass's implementation: 1. A method override calls `super.headers()`. 2. A property override reads or writes `super.description` in its getter or setter. 3. A subscript override uses `super[index]`. That gives you three shapes of override. You can **extend** it by calling `super` and then adding to the result, as `BillingService.headers()` does. You can **wrap** it by doing work before and after the `super` call. Or you can **replace** it by not calling `super` at all. ## What `super` does not guarantee - **No method override is forced to call `super`.** Leaving it out compiles without a warning. If a base class depends on subclasses calling through, for state it updates or a notification it posts, that contract exists only in its documentation and in code review. - **Order is yours.** Calling `super` first, last or in the middle are all legal, and they behave differently. - **Initializers are the exception.** A subclass's designated initializer must delegate up to a superclass designated initializer, and Swift inserts an implicit `super.init()` in the simple case. Those rules are covered with initializers. - **The override runs through the superclass type too.** `let service: APIService = BillingService()` calls `BillingService`'s `describe()`. How the call is resolved at run time is covered in the material on method dispatch. ## Mistakes interviewers listen for - Calling `override` an optional hint, or saying a missing one is only a warning. - Claiming structs or actors can subclass, or that every class implicitly inherits from `NSObject`. - Assuming a typo in an override name creates a harmless new method. It is a compile error once `override` is written. - Believing the compiler makes every override call `super`. - Expecting a variable typed as the superclass to run the superclass's version.

  • Can a Swift override rename a method's argument labels?
    No. Argument labels are part of a Swift method's name, so `override func label(identifier:)` does not match `label(id:)`. The compiler reports that the argument labels do not match those of the overridden method. Parameter names inside the body may differ, but the labels callers write must stay the same.
  • Is there any place where Swift does require calling the superclass?
    Yes, in initialization. A subclass's designated initializer must delegate up to a superclass designated initializer, and Swift inserts an implicit `super.init()` when the superclass has a designated `init()` that takes no arguments. Ordinary method overrides have no such rule. Whether to call `super`, and when, is up to the subclass.

  • override is optional and only documents intent
  • Every Swift class implicitly inherits from NSObject
  • A struct can subclass another struct to reuse its stored properties
  • The compiler forces every method override to call super
  • A superclass-typed variable runs the superclass method, not the override
  • A misspelled override name just creates a new method
open as a page

In Swift, what does `final` prevent on a class versus on one member, and how do `static` and `class` type methods behave under override?

level: middleimportance: should knowfreq 55%

basics

~20 s

final on a Swift class forbids subclassing; on a method, property or subscript it forbids overriding that member only. On a class, a static member cannot be overridden, while a class member can unless it is also marked final.

open as a page

A Swift subclass overrides an inherited `baseURL` property to add `willSet` and `didSet`; what can a property override change, and when do these observers run?

level: seniorimportance: should knowfreq 40%

basics

~10 s

A Swift property override supplies a getter (and setter) or adds willSet/didSet, never new storage. Its observers wrap the superclass's own observers and also fire when a subclass initializer sets the property after super.init().

open as a page

A Swift codebase subclasses a base `NetworkService` class for each backend and for a test fake; should the team make classes `final` by default and use protocols with composition instead?

level: principalimportance: should knowfreq 40%

basics

~20 s

Usually yes in Swift: make classes final by default and inject a protocol-typed dependency, because subclass fakes inherit real state and init, overrides form unchecked contracts, and only final classes can be Sendable. Keep subclassing for hierarchies designed for it.

open as a page

In Swift, which signature changes may a method or property override make, such as return type, optionality, throws or labels, and which are rejected?

level: seniorimportance: nice to knowfreq 25%

basics

~20 s

A Swift override may return a subclass or a non-optional result, take optional parameters, and drop throws. It may not add throws or async, rename labels, or narrow a mutable property. Non-@objc members declared in extensions cannot be overridden.

open as a page