In Swift, which signature changes may a method or property override make, such as return type, optionality, throws or labels, and which are rejected?
answer
- accept more, promise more
- covariant results, optional parameters
- may drop throws, never add
- extension members cannot be overridden
basics
~20 sA 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.
solid answer
~40 sAn override must work wherever the original does, so it may accept more and promise more. It can return a subclass of the declared type, return non-optional where the base returned optional, take an optional where the base took a non-optional, and drop `throws`. It cannot add `throws` ("cannot override non-throwing instance method with throwing instance method"), add `async`, change argument labels, or give a read-write property a narrower type, although a read-only property may narrow. Placement matters too. A non-`@objc` method declared in an extension of the superclass cannot be overridden, and an override cannot be written in an extension of the subclass. Effects are checked against the static type, so a call through the superclass type still needs `try`.
code
swift · 21 linesclass Payload {}
class ProfilePayload: Payload {}
class APIService {
func decode(body: [UInt8]) -> Payload? { nil }
func fetch(path: String) throws -> [UInt8] { [] }
var lastPayload: Payload { Payload() }
}
class ProfileService: APIService {
// Parameter widened to an optional, result narrowed to a non-optional subclass.
override func decode(body: [UInt8]?) -> ProfilePayload { ProfilePayload() }
// A non-throwing override of a throwing method.
override func fetch(path: String) -> [UInt8] { [1, 2] }
// A read-only property may narrow its type.
override var lastPayload: ProfilePayload { ProfilePayload() }
}
let service: APIService = ProfileService()
let bytes = try service.fetch(path: "/me") // still needs try through the base type
print(type(of: service.decode(body: bytes)!), bytes.count) // ProfilePayload 2go deeper
Recall that an override keeps the method's name and labels, and that the compiler rejects one that does not match.
Explain which variations are legal, covariant results, widened optional parameters and dropping throws, using the rule that an override accepts more and promises more.
Diagnose a does-not-override error by checking labels, optionality, effects and whether the base member sits in an extension. Know that calls through the base type keep the base's effects.
Put extension points in the class body on purpose and keep everything else in extensions or final. Where a member is declared then documents which hooks the type supports.
## The rule behind every case An override has to be usable everywhere the overridden member is usable. Code holding an `APIService` reference calls `decode(body:)` with the superclass's argument types and handles the superclass's result type, so an override may **accept more** and **promise more**, but never accept less or promise less. Every rule below follows from that, and the Swift 6.4 compiler checks them when you write `override`. ## What an override may change | Change in the override | Allowed? | Why | |---|---|---| | Return a subclass of the declared return type (`-> ProfilePayload` for `-> Payload`) | Yes | callers still receive a `Payload` | | Return non-optional where the original returned optional | Yes | a value is a valid optional | | Take an optional where the original took non-optional (`[UInt8]?` for `[UInt8]`) | Yes | it accepts every value the original did | | Return optional where the original returned non-optional | No | callers would receive `nil` they cannot handle | | Drop `throws` | Yes | a non-throwing method satisfies a throwing contract | | Add `throws` | No | "cannot override non-throwing instance method with throwing instance method" | | Add `async` to a synchronous method | No | the compiler finds no method to override | | Rename argument labels | No | labels are part of the name; the compiler says they "do not match those of overridden method" | | Narrow a read-only property's type | Yes | it is only ever read | | Narrow a read-write property's type | No | "cannot override mutable property ... with covariant type" | Two details catch people. First, effects are judged through the static type. Calling `fetch(path:)` through an `APIService` reference still needs `try`, even when the runtime object is a `ProfileService` whose override cannot throw, while a `ProfileService`-typed reference needs no `try`. Second, The Swift Programming Language's reference says a synchronous method can override an asynchronous one, but the Swift 6.4 compiler rejects `override func refresh() -> Int` against `func refresh() async -> Int` with "method does not override any method from its superclass". Keep `async` the same in both. ## Where the overridden member was declared Declaration placement matters as much as the signature: - **A method declared in an extension of the superclass cannot be overridden.** The error reads "non-'@objc' instance method 'retry()' is declared in extension of 'APIService' and cannot be overridden". Members meant as extension points must live in the class body. The `@objc` escape hatch belongs to Objective-C interop. - **An override cannot live in an extension of the subclass** either: "non-'@objc' instance method 'reset()' declared in 'APIService' cannot be overridden from extension". - **Access** is checked too. An override may be more accessible than the member it overrides. One that is less accessible fails with "overriding instance method must be as accessible as the declaration it overrides", unless its own class is less visible still. The visibility rules belong to the lesson on access levels. ## Reading a failing override 1. "method does not override any method from its superclass" usually means the signature drifted: a label, an optional, an effect or a type no longer lines up. 2. A note pointing at the "potential overridden" declaration tells you which superclass member the compiler tried to match. 3. If the superclass member sits in an extension, move it into the class body before overriding it. ## Mistakes interviewers listen for - Saying an override must repeat the signature exactly. Covariant results and widened optional parameters are legal. - Assuming an override may add `throws` "because the subclass needs it". - Putting customisation hooks in an extension and expecting subclasses to override them. - Expecting a non-throwing override to remove `try` at call sites typed as the superclass.
- Why may a read-only property override narrow its type when a read-write one may not?A read-only property is only read, and a `ProfilePayload` is a valid `Payload` for any caller. A read-write property can also be assigned through the superclass type, which could store a plain `Payload` into storage the subclass promised holds only `ProfilePayload`. Swift rejects that with "cannot override mutable property ... with covariant type".
- A base class's helper lives in `extension APIService` and a subclass needs to customise it. What are the options?Move the method into the class body so it can be overridden. Or make the customisation explicit, for example with a closure property or a protocol-typed dependency the class calls. Marking the method `@objc` also allows overriding, but that pulls in the Objective-C runtime and belongs to interop, so it is not a design tool for pure Swift types.
- An override must repeat the superclass signature exactly
- A subclass may add throws to an override if callers use try
- Any method in a class extension can be overridden like one in the body
- Returning an optional from an override of a non-optional method is fine
- A non-throwing override removes the need for try through the base type