In Swift, how does a subclass replace an inherited method with `override`, and how does it reach the superclass version through `super`?
answer
- one superclass, classes only
- keyword checked in both directions
- missing keyword vs no match
- super.method() inside the override
basics
~20 sA 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 sA 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 linesclass 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
Recall that only classes inherit, one superclass each, and that override is a required keyword. Be able to write super.method() inside an override.
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.
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.
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