skip to content

What does Swift's inout do to the caller's variable, and why must the call site write & before the argument?

level: middleimportance: must knowfreq 68%

answer

  1. parameters are constants by default
  2. changes flow back to the caller
  3. only a var can be passed
  4. the ampersand marks a mutation
  5. a class reference can be replaced

basics

~20 s

Swift parameters are constants. Marking one inout lets the function assign to it, and the final value is written back to the caller's variable on return; the caller must pass a var prefixed with &.

solid answer

~50 s

By default a Swift parameter is a `let` constant inside the body, so `n += 1` on it does not even compile. Declaring the parameter `inout`, as in `func swapValues(_ a: inout Int, _ b: inout Int)`, lets the body assign to it, and the final value is written back to the caller's variable when the function returns. The caller must pass something mutable — a `var`, a stored property of a `var`, an element of a `var` array — never a `let`, a literal or a computed result, and must prefix it with `&`: `swapValues(&first, &second)`. The `&` is the call-site signal that this line can change that variable. `inout` is not the same as returning a value, and the semantics are copy-in copy-out rather than a pointer. On a class reference, `inout` lets the function replace which object the caller's variable points to.

code

swift · 31 lines
swift
final class Session {
    var token: String
    init(token: String) { self.token = token }
}

func refresh(_ session: Session) {
    session.token = "fresh"            // allowed: mutates the shared object
}

func replace(_ session: inout Session) {
    session = Session(token: "new object")  // rebinds the caller's variable
}

func swapValues(_ a: inout Int, _ b: inout Int) {
    let temporary = a
    a = b
    b = temporary
}

let shared = Session(token: "old")
refresh(shared)
print(shared.token)                    // fresh

var current = Session(token: "old")
let alias = current
replace(&current)
print(current.token, alias.token)      // new object old

var first = 3, second = 107
swapValues(&first, &second)
print(first, second)                   // 107 3

go deeper

for a junior

Know that parameters are constants, that inout lets a function change the caller's var, and that the caller writes & in front of the argument.

for a middle

Explain the call-site rules: only mutable locations, a mandatory &, no defaults or variadics, and how inout differs for a class reference versus a struct.

for a senior

Explain why the language describes inout as copy-in copy-out rather than a reference, and when returning a value or a mutating method is the cleaner design.

for a principal

Treat inout in a public API as a deliberate choice: it constrains every caller to a var and an &, so reserve it for genuine in-place updates.

## Parameters are constants In Swift every function parameter is, by default, a **constant** inside the function body. Values arrive by value: a struct, an enum or an `Int` passed to a function is that function's own copy, and the body cannot assign to it at all. ```swift func bump(_ n: Int) { n += 1 // error: left side of mutating operator isn't mutable: 'n' is a 'let' constant } ``` That rule is what makes ordinary Swift calls easy to reason about: after `bump(score)`, `score` is unchanged, guaranteed. ## What `inout` changes An **in-out parameter** is declared with the `inout` modifier before the type. The book describes it as a value "passed *in* to the function, is modified by the function, and is passed back *out* of the function to replace the original value." ```swift func swapValues(_ a: inout Int, _ b: inout Int) { let temporary = a a = b b = temporary } var first = 3, second = 107 swapValues(&first, &second) // first is 107, second is 3 ``` The standard library ships this exact utility as the generic `swap(_:_:)`, and collections offer `swapAt(_:_:)` for two elements of the same collection. ## The rules at the call site 1. **Only something mutable can be passed.** A `var`, a stored property reached through a `var`, or an element of a `var` array works. A `let` constant fails with `cannot pass immutable value as inout argument: 'k' is a 'let' constant`; literals and function results are not variables at all. 2. **The `&` is mandatory.** Leaving it out gives `passing value of type 'Int' to an inout parameter requires explicit '&'`. The ampersand is not a general address-of operator that produces a value you can store; in an in-out argument it marks, at the call site, that this argument may come back changed. 3. **No defaults, no variadics.** An `inout` parameter cannot have a default value, and a variadic parameter cannot be `inout`. 4. **One variable, one in-out slot.** Passing the same variable to two in-out parameters of one call is rejected; the reasons belong with Swift's exclusivity rules. ## How the value travels The reference manual defines the model as **copy-in copy-out**, also called call by value result: - when the function is called, the argument's value is copied in; - the body modifies that copy; - when the function returns, the copy's value is assigned back to the original. For a plain stored variable the compiler may optimise this into using the same memory directly, but the language promises only the copy-in copy-out behaviour, and code should be written against that model. The difference becomes visible with computed properties and property observers, which is a deeper topic in its own right. ## `inout` versus returning a value | Approach | Call site | Good for | |---|---|---| | Return a new value | `score = bumped(score)` | most transformations; easy to chain and test | | `inout` parameter | `bump(&score)` | in-place updates of a caller-owned value, such as swapping two values or appending into a buffer | | `mutating` method | `score.bump()` | when the change belongs to the type itself | The book notes that in-out parameters are "not the same as returning a value": they are a way for a function to have an effect outside its own scope. Prefer returning a value unless the in-place form reads better or avoids a needless copy of a large buffer. ## `inout` with class references A class instance is passed as a reference, so even without `inout` a function can change the object's `var` properties: `refresh(session)` can set `session.token`. What it cannot do is make the caller's variable point at a *different* object. With `inout Session`, the function can assign a new instance, and the caller's variable is rebound to it while any other references keep the old object. Things that commonly trip people up: - `inout` does **not** turn a struct into a shared reference; after the call, the caller's variable simply holds the new value. - An escaping closure cannot capture an `inout` parameter; the compiler reports `escaping closure captures 'inout' parameter`, because the value is only valid until the call returns. - Writing `inout` on a parameter that the function never assigns to is legal, but it forces every caller to supply a `var` and `&` for nothing.

  • Can a Swift function store or capture an inout parameter for later use?
    Not directly. The in-out value is only valid for the duration of the call, so an escaping closure that captures it is rejected with `escaping closure captures 'inout' parameter`. A nonescaping closure may use it, and a capture list such as `[a]` captures a copy of its current value instead.
  • Why can you write swapValues(&scores[0], &total) but not swapValues(&total, &total) in Swift?
    Both arguments are mutable locations, so each can be passed with `&`. Passing the same variable to two in-out parameters gives the function two overlapping write accesses to one variable, which the compiler rejects as `inout arguments are not allowed to alias each other`. That rule comes from Swift's law of exclusivity.

  • inout passes a pointer, so the caller sees each change immediately
  • You can pass a let constant inout if the function only reads it
  • The & is optional when the type already makes the intent clear
  • Without inout a function cannot change anything about a class instance
  • inout makes a struct behave like a shared reference after the call