skip to content

Methods and Subscripts

Methods belong to types, mutating methods may replace self in a value type, and subscripts give types index syntax. Interviewers ask why a struct needs mutating and how subscripts work.

on this pageshow

explore

questions

5

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%

answer

  1. value types guard their own self
  2. self is read-only by default
  3. write access for the whole call
  4. a constant grants no write access

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.

solid answer

~50 s

Structs and enums are value types, so inside an ordinary method `self` is a constant: `count += 1` fails with "left side of mutating operator isn't mutable: 'self' is immutable", and the compiler's note says to mark the method `mutating`. A `mutating` method gets write access to `self` for the duration of the call, and its changes are written back to the caller's variable when it ends. So the call needs a mutable place to write into: `var taps = Counter(); taps.increment()` works, while on a constant the compiler reports "cannot use mutating member on immutable value: 'frozen' is a 'let' constant". Function parameters and `for`-`in` loop variables are constants too, so the same error appears there. Classes never use the keyword: a class method changes the object behind the reference, and `mutating` is not valid on a class's instance methods.

code

swift · 20 lines
swift
struct Counter {
    var count = 0

    mutating func increment() {
        count += 1
    }

    func incremented() -> Counter {
        var copy = self
        copy.increment()
        return copy
    }
}

var taps = Counter()
taps.increment()                 // fine: taps is a var

let frozen = Counter()
let next = frozen.incremented()  // fine: non-mutating, returns a new value
print(taps.count, frozen.count, next.count)  // 1 0 1

go deeper

for a junior

Recall that struct and enum methods cannot change self unless marked mutating, and that a mutating method can only be called on a var.

for a middle

Explain that a mutating method has write access to self for the call and writes the result back, and name the hidden constants: parameters, loop variables, get-only properties.

for a senior

Show you design value-type APIs deliberately: pair a mutating method with a non-mutating copy-returning variant, and read the let-constant diagnostics as API feedback rather than noise.

for a principal

Frame mutating as part of a type's contract: it tells reviewers which calls change state, which is why value-type models stay easy to reason about across a codebase.

## What `mutating` declares Swift has two kinds of types with very different copying rules. **Value types** — structures and enumerations — are copied when you assign them or pass them along; **reference types** — classes — are shared through references. A method on a value type operates on `self`, and by default that `self` is a **constant** inside the method body. The Swift book states it plainly: by default, the properties of a value type can't be modified from within its instance methods. To change a stored property, you opt in by writing `mutating` before `func`. The method then gets **write access to `self` for the duration of the call**, and, in the book's words, any changes it makes are written back to the original structure when the method ends. Without the keyword the compiler stops you at the first write: - `count += 1` in a plain method reports `left side of mutating operator isn't mutable: 'self' is immutable`. - The attached note reads `mark method 'mutating' to make 'self' mutable`, which is exactly the fix. The keyword is part of the method's contract, not an implementation detail. A reader of the declaration knows that `increment()` may change the value it is called on, while a method without it promises not to — which is what lets Swift reason about constants at all. ## Why a `let` constant blocks the call A mutating method needs somewhere to write its result back to. A `var` provides that place; a `let` constant does not. For a structure, `let` freezes the **entire value**, including properties declared with `var`, so a call that would change any part of it is rejected before the program runs: ```swift let frozen = Counter() frozen.increment() // error: cannot use mutating member on immutable value: 'frozen' is a 'let' constant // note: change 'let' to 'var' to make it mutable ``` The rule is checked at compile time, so there is no run-time trap to catch and nothing to test for — the code simply does not build. ## Places that are constants without saying `let` Several places are immutable even though you never typed `let`, and each produces the same family of errors: 1. **Function parameters.** A `Counter` parameter is a constant copy; calling `increment()` on it reports that the parameter is a `'let' constant`. Copy it into a local `var`, or take it `inout` if the caller's value should change. 2. **`for`-`in` loop variables.** In `for c in counters { c.increment() }`, each `c` is a constant copy of an element; the compiler rejects the call. Mutate through the index instead: `counters[i].increment()`. 3. **Get-only computed properties.** Calling a mutating method on one is rejected with `'computed' is a get-only property`, because there is no setter to write the result back through. 4. **Function results.** `makeCounter().increment()` fails with `'makeCounter' returns immutable value` — a temporary has no storage to write into. ## How classes differ | | Struct or enum | Class | |---|---|---| | `self` in an ordinary method | constant | the reference is constant, the object is not | | Changing a stored `var` property | needs `mutating` | allowed in any method | | `mutating` keyword | required to write | rejected: not valid on instance methods in classes | | Method call through a `let` binding | mutating calls rejected | any method may change the object | A class method changes the shared object that the reference points to, so the reference itself never needs to be writable. A `let` holding a class instance freezes only which object it refers to. This is also why a struct stored as a `var` property of a class can be mutated through a `let` reference to that class: the class's storage is writable even when the reference is not. ## Offering a non-mutating variant Mutating methods are not the only design. A common Swift pattern pairs a mutating method with a non-mutating one that returns a changed copy, the way the standard library pairs `Array.sort()` with `sorted()`: - `mutating func increment()` changes the value in place and needs a `var`. - `func incremented() -> Counter` copies `self` into a local `var`, mutates the copy and returns it, so it works on constants. One related detail: a setter on a structure's computed property or subscript is implicitly mutating too, so assigning through it on a constant fails in the same way. A setter can opt out with `nonmutating set` when it writes somewhere other than the value's own storage, such as an object it holds a reference to.

  • Why does `for c in counters { c.increment() }` fail to compile when `counters` is a `var` array of structs?
    Each loop variable in a `for`-`in` loop is a constant copy of an element, so the compiler reports that `c` is a `'let' constant`. Even if it were mutable, it would be a copy, and changing it would leave the array untouched. Mutate through the array instead: `for i in counters.indices { counters[i].increment() }`.
  • A class `Screen` stores `var taps = Counter()`. Why does `let screen = Screen(); screen.taps.increment()` compile?
    `let screen` freezes only the reference, not the object. `taps` is a `var` stored property inside the class instance, so it is a writable place, and the mutating call writes its result back into the object's storage. Had `taps` been declared with `let`, the call would fail.
  • Can a struct's computed property setter be used on a `let` constant?
    Not by default: setters on value types are implicitly mutating. If the setter writes somewhere other than the struct's own storage — for example into a class instance the struct holds — you can declare it `nonmutating set`, and then assignment through a constant compiles.

  • Says mutating is needed for any method on a struct, even one that only reads
  • Claims the let check is a run-time error rather than a compile-time one
  • Believes a class method that changes a property needs mutating
  • Thinks var properties inside a let struct can still be changed by a method
  • Says mutating makes the struct behave like a reference type
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

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