In Swift, why does a retry handler that uses `attempt` see a later reassignment while `{ [attempt] in … }` does not, and what does a capture list not copy?
answer
- the variable, not its value
- capture list runs at creation
- entries are constants
- a class reference stays shared
- each for-in iteration binds anew
basics
~20 sA closure captures the variable attempt itself and reads its current value when it runs. The capture-list entry [attempt] is a new constant initialised when the closure is created; for a class instance it copies only the reference, not the object.
solid answer
~50 sSwift closures capture **variables**: a closure that uses `attempt` shares that variable with the enclosing scope, so a later `attempt = 3` is what it prints. A capture list entry `[attempt]` declares a separate **constant** inside the closure, initialised from `attempt` when the closure expression is evaluated; later reassignments outside do not reach it, and assigning to it inside fails with `left side of mutating operator isn't mutable: 'attempt' is an immutable capture`. The copy is shallow: `[log]` copies a class reference, so changes made through either reference to the same `RequestLog` object are visible on both sides, while reassigning the outer variable to a new object is not. Two related Swift facts: closures are reference types, so two constants holding one closure share its captured state, and each `for-in` iteration binds a fresh constant, so per-row handlers keep their own row.
code
swift · 22 linesfinal class RequestLog { var lines: [String] = [] }
func makeHandlers() -> [() -> Void] {
var attempt = 1
let log = RequestLog()
let byVariable = { print("variable sees attempt", attempt) }
let byList = { [attempt] in print("capture list sees attempt", attempt) }
let logged = { [log] in print("log lines", log.lines.count) }
attempt = 3 // reassigned after all three closures exist
log.lines.append("retry") // mutates the object both scopes share
return [byVariable, byList, logged]
}
for handler in makeHandlers() { handler() }
// variable sees attempt 3
// capture list sees attempt 1
// log lines 1
var rowHandlers: [() -> Void] = []
for row in 0..<3 {
rowHandlers.append { print("row", row) } // each iteration binds a new row
}
rowHandlers.forEach { $0() } // row 0, row 1, row 2go deeper
Recall that a closure sees later changes to a variable it uses, while a capture-list entry keeps the value from when the closure was created.
Explain that capture-list entries are constants evaluated at creation, show the immutable-capture error, and say what [log] means for a class instance.
Diagnose stale or surprising values in deferred handlers by tracing value versus reference at each step: the outer variable, the capture-list constant, the object, the closure.
Set expectations that deferred work captures explicit snapshots or narrow dependencies, so a reviewer can tell from the capture list what a callback will observe.
## Capturing a variable is the default When a closure uses a name from its enclosing scope, Swift **captures** it. The Swift book describes the default as capturing a *reference* to the variable: the closure and the enclosing function use **one** storage location, and that location lives on after the function returns if the closure does. In the retry scenario, `let byVariable = { print(attempt) }` followed by `attempt = 3` prints `3` when the handler runs, because the closure reads the shared variable at call time, not at creation time. A write inside the closure is equally visible outside. The book adds an optimization note: Swift **may** store a copy instead when the value is not mutated by the closure or after the closure is created. That optimization is unobservable — it only applies when a copy and a shared variable would behave identically. ## The capture list: a constant made at creation A **capture list** is a bracketed list before the parameters: `{ [attempt] in … }`. For each entry, Swift declares a **new constant** with the same name inside the closure and initialises it from the outer value **when the closure is created**. - Later changes to the outer `attempt` are not seen; the closure keeps the value it captured. - The inner name is a `let`. `attempt += 1` inside fails with `left side of mutating operator isn't mutable: 'attempt' is an immutable capture`. - An entry can bind any expression: `[limit = retries.count]` evaluates `retries.count` once, at creation. - Using a capture list requires the `in` keyword, even when no parameters are named. - `weak` and `unowned` are written on capture-list entries (`[weak self]`) — the same mechanism, with a different reference strength. ## What a capture list does not copy The capture list copies **the value of the expression**, and Swift's value-vs-reference rules decide what that means: | Captured entry | What the constant holds | Outer change visible inside? | |---|---|---| | `[attempt]`, an `Int` | its own `Int` value | no | | `[settings]`, a struct | an independent copy of the struct | no | | `[log]`, a class instance | a second reference to the same object | yes, for changes made through either reference | | `[log]`, then outer `log = RequestLog()` | still the original object | no — the outer variable now points elsewhere | So a capture list is **not** a deep copy. If the closure must not observe later changes to an object, capture an immutable snapshot of the data it needs, for instance `[lines = log.lines]`. ## Closures themselves are reference types A closure value is a **reference**: assigning it to another constant does not copy its captured state. With `let next = makeCounter()` and `let alias = next`, calling `next()` and then `alias()` returns `1` and then `2`, because both names point at the same closure and the same captured `total`. A second call to `makeCounter()` creates a new closure with its own `total`. ## Loops: each iteration binds a new constant A `for-in` loop declares its loop variable afresh on every iteration. Closures created inside the loop therefore each capture a **different** `row`: ```swift var rowHandlers: [() -> Void] = [] for row in 0..<3 { rowHandlers.append { print("row", row) } } rowHandlers.forEach { $0() } // row 0, row 1, row 2 ``` The general "every handler sees the last loop value" pitfall does not arise with Swift's `for-in`; it appears when closures capture a single `var` declared **outside** the loop and updated inside it. ## When to reach for a capture list - To **freeze** a value at creation — a request ID, a retry count, a configuration snapshot — when the closure runs later. - To capture a **dependency** rather than `self`: `[store]` keeps only the store alive. - To choose **reference strength**: `[weak self]`, `[unowned self]`. - Not when the closure is meant to observe or update shared state — then capture the variable itself, deliberately.
- In Swift, can a closure change a value it lists in its capture list?No. Each capture-list entry is a constant inside the closure, so `count += 1` on `[count]` fails with `left side of mutating operator isn't mutable: 'count' is an immutable capture`. If the closure needs its own mutable state, declare a `var` inside it or capture the outer variable deliberately.
- In Swift, what does `for row in 0..<3 { handlers.append { print(row) } }` print when the handlers run later?`0`, `1` and `2`. A `for-in` loop binds a new `row` constant on every iteration, so each closure captures its own. The all-the-same-value result appears when closures capture one `var` declared outside the loop and changed inside it.
- In Swift, what do two constants holding the same counter closure share?Everything the closure captured. Closures are reference types, so `let alias = next` makes both names point at one closure and one captured `total`; calling `next()` and then `alias()` returns 1 and then 2. Only calling the factory again creates independent state.
- A capture list deep-copies the object a class reference points to.
- Without a capture list, Swift copies every captured value at creation.
- Capture-list entries can be mutated inside the closure like var.
- Swift for-in loops make every closure see the last loop value.
- Assigning a closure to a new constant copies its captured state.