skip to content

Structs and Classes

Structs copy and classes share, and that choice shapes properties, methods, initializers and inheritance. Interviewers spend real time here because Swift defaults to value types.

on this pageshow

explore

questions

27

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, why must a struct method that changes a stored property be marked `mutating`, and why can't you call it on a `let` constant?

level: juniorimportance: must knowfreq 72%

basics

~20 s

A struct or enum method sees self as immutable unless it is marked mutating, which grants write access to the value for the call. A let constant never grants that access, so a mutating call on one does not compile.

open as a page

In Swift, what is the difference between a stored property and a computed property, and how is a read-only computed property declared?

level: juniorimportance: must knowfreq 70%

basics

~20 s

A stored property holds a value in each instance's memory; a computed property stores nothing and runs its getter, and optional setter, on every access. A read-only computed property has only a getter and is still declared with var.

open as a page

In Swift, if a shopping cart passed to two screens is a struct rather than a class, what happens when one screen adds an item?

level: juniorimportance: must knowfreq 85%

basics

~20 s

A struct is copied whenever it is assigned or passed, so each screen holds its own cart and the other screen never sees the new item. A class instance is shared, so both screens see it.

open as a page

In Swift classes, how do designated and convenience initializers differ, and which delegation rules does the compiler enforce between them?

level: middleimportance: must knowfreq 55%

basics

~20 s

A designated initializer fully initializes the properties its class introduces and, in a subclass, calls a designated initializer of the immediate superclass. A convenience initializer, marked convenience, must call another initializer of the same class with self.init, ultimately reaching a designated one.

open as a page

In a Swift struct, when does the compiler synthesize a memberwise initializer, and why does adding your own init make it disappear?

level: middleimportance: must knowfreq 62%

basics

~20 s

Swift synthesizes a memberwise initializer for a struct that declares no initializer in its own body, with one labelled parameter per stored property in declaration order. An init written in the body suppresses it; one written in an extension keeps both.

open as a page

In Swift, when are a property's willSet and didSet observers called, and when does Swift skip them?

level: middleimportance: must knowfreq 60%

basics

~20 s

willSet runs just before a new value is stored and didSet right after, on every assignment outside initialization, even when the value is unchanged. They are not called while a type's own initializer sets the property.

open as a page

In Swift, what does `let` freeze when the constant holds a struct value, and what does it freeze when it holds a class instance?

level: middleimportance: must knowfreq 70%

basics

~10 s

A let struct is entirely immutable: no property can be assigned, even one declared var. A let class reference cannot be pointed at another instance, but the instance's var properties can still change.

open as a page

In Swift, which types can declare a deinit, what is a deinitializer allowed to do, and how does it run in a class hierarchy?

level: juniorimportance: should knowfreq 40%

basics

~20 s

Classes and actors can declare one deinit, and since Swift 5.9 so can noncopyable structs, though not yet noncopyable enums. It takes no parameters, cannot be called directly, can read the instance's properties, and a subclass's deinit runs before its superclass's, which runs automatically.

open as a page

In Swift, what is a failable initializer, how do you write init? that rejects a bad server payload, and what does the caller get back?

level: juniorimportance: should knowfreq 50%

basics

~20 s

A failable initializer, written init?, may fail: it executes return nil on bad input and otherwise initializes normally. The caller receives an Optional, User? for User(payload:), and unwraps it with if let or guard let.

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

Inside a Swift `mutating` method, what does assigning a new value to `self` do, and how does an enum use it to change its own case?

level: middleimportance: should knowfreq 45%

basics

~20 s

Assigning to self in a mutating method replaces the entire value with a new one, which is written back to the caller's variable when the method ends. Enums use it to move to a different case, rebuilding any associated values.

open as a page

In Swift, what is the difference between declaring a type method with `static` and with `class`, and where can each be used?

level: middleimportance: should knowfreq 48%

basics

~20 s

Both declare type methods, called on the type rather than an instance. Structs and enums can only use static; classes can use either, and a class method may be overridden by a subclass while a static one, equivalent to class final, cannot.

open as a page

How do you declare a Swift subscript that reads and writes `grid[row, column]`, and how do subscript argument labels differ from a method's?

level: middleimportance: should knowfreq 40%

basics

~20 s

Declare subscript(row: Int, column: Int) -> Double with a get and a set block; the setter receives newValue. Unlike a method's parameters, a subscript's parameters have no argument labels unless you write one explicitly, so callers write grid[1, 2].

open as a page

In Swift, what does marking a stored property lazy do, and why must a lazy property be declared with var?

level: middleimportance: should knowfreq 55%

basics

~20 s

A lazy stored property runs its initial-value expression on first access instead of during initialization, then keeps the result. It must be var because it gets its value after initialization ends, which a let constant cannot do.

open as a page

In Swift, how do static and class type properties differ, and when does a stored static property get its initial value?

level: middleimportance: should knowfreq 45%

basics

~20 s

Both belong to the type, not an instance. static works in structs, enums and classes and cannot be overridden; class is only for computed properties of classes and is overridable. A stored static property initializes on first access, exactly once.

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

Why does a Swift subclass that adds its own designated initializer stop inheriting its superclass's initializers, and how does required change that?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Swift subclasses inherit superclass initializers only when it is safe: all designated ones when the subclass defines none and gives new properties defaults, convenience ones once it covers every designated one. Marking an initializer required forces every subclass to provide it.

open as a page

A Swift subclass initializer calls a method and sets an inherited property before super.init, and the compiler rejects it; what does two-phase initialization require, and how do you fix it?

level: seniorimportance: should knowfreq 45%

basics

~20 s

Phase one must give every stored property in the hierarchy a value, each class setting its own before calling super.init; only then may code use self. Fix it by setting the subclass's properties, calling super.init, then calling methods and assigning inherited properties.

open as a page

Why does a Swift struct's `mutating` method fail to compile when it passes a closure that captures `self` to `DispatchQueue.main.async`, and how do you fix it?

level: seniorimportance: should knowfreq 35%

basics

~20 s

A mutating method has write access to self only until it returns, but an escaping closure may run later, so Swift rejects the capture. Capture an immutable copy, hand the result to the owner, or make the method async.

open as a page

A Swift SettingsStore class saves to disk in didSet on its recentFiles array; why do three appends write three times while its initializer writes nothing?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Mutating part of a value-typed property, such as an append or a nested field write, writes the whole property, so didSet runs once per mutation. Assignments in the type's own initializer skip observers, so nothing saves there.

open as a page

In Swift, how do you give a large Matrix struct copy-on-write behaviour with a class box and `isKnownUniquelyReferenced(_:)`, and what breaks it?

level: seniorimportance: should knowfreq 45%

basics

~20 s

Keep the elements in a private class instance; in every mutating method call isKnownUniquelyReferenced(&storage) and, when it returns false, replace the box with a clone before writing. Copies share the box until one of them writes.

open as a page

In Swift, a Cart struct stores a Coupon class instance; after copying the cart and changing the coupon's discount on the copy, why does the original cart change too?

level: seniorimportance: should knowfreq 55%

basics

~20 s

Copying a struct copies each stored property, and a class-typed property is a reference, so both carts point at the same Coupon. Value semantics stops at that reference; changes to the coupon show through every copy.

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

As a lead setting a Swift team rule of structs by default for models, where would you still require a class, and what does the rule cost?

level: principalimportance: should knowfreq 50%

basics

~20 s

Default model types to structs and enums, and require a class when identity is the point: one shared mutable instance, inheritance, Objective-C exposure, a weak reference, or deinit cleanup. The rule costs explicit ownership and write-back plumbing.

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

In Swift, how do you declare a computed property whose getter is async or throws, and what can such a property not have?

level: seniorimportance: nice to knowfreq 20%

basics

~20 s

Write the effects after get, as in var celsius: Double { get async throws { ... } }, and read it with try await. Such a property (Swift 5.5) must be read-only: no setter, no observers, no key path.

open as a page