In Swift, what does a nested function capture from its enclosing function, and what happens when the enclosing function returns it?
answer
- a closure with a name
- locals outlive the call
- each factory call, fresh state
- inout cannot escape
basics
~20 sA Swift nested function captures the enclosing function's parameters and locals it uses. Returned, it keeps those variables alive; each call of the enclosing function creates fresh ones, while copies of one returned function share them.
solid answer
~50 sA nested function is a closure with a name: it can read and modify any parameter, constant or variable of its enclosing function that it uses. Swift captures a variable by reference, so when `makeRetryPolicy(maxAttempts:)` returns its nested `shouldRetry`, the local `var attemptsSeen` lives on inside the returned function. Every call of the factory creates a new `attemptsSeen`, but assigning one returned function to a second constant shares it, because functions are reference types. The compiler enforces two rules: using the nested function before a local it captures is declared fails with "closure captures 'limit' before it is declared", and letting it escape while it captures an `inout` parameter fails with "escaping local function captures 'inout' parameter" followed by the parameter's name. Over a closure expression, a nested function adds a name for direct recursion, argument labels, default values and generic parameters.
code
swift · 15 linesfunc makeRetryPolicy(maxAttempts: Int) -> (Int) -> Bool {
var attemptsSeen = 0 // lives on after the factory returns
func shouldRetry(statusCode: Int) -> Bool {
attemptsSeen += 1 // captured variable, not a copy
return statusCode >= 500 && attemptsSeen < maxAttempts
}
return shouldRetry // the nested function escapes
}
let checkout = makeRetryPolicy(maxAttempts: 3)
let alias = checkout // same function value, same state
let profile = makeRetryPolicy(maxAttempts: 3) // fresh attemptsSeen
print(checkout(503), alias(503), checkout(503), profile(503))
// true true false truego deeper
Recall that a function declared inside another can use the outer function's variables and can be returned as a value.
Explain capture by reference, why each factory call gets fresh state while copies of one returned function share it, and the two compile errors around use-before-declaration and inout.
Spot shared captured state in review, such as a retry counter that silently persists across requests, and choose between a nested function and a closure expression for recursion, labels or a capture list.
Judge when hidden captured state in a returned function should become an explicit type whose state other engineers can see, test and reset.
## Nested functions are named closures Swift lets you declare a function inside the body of another function. Such a **nested function** is hidden from the outside world unless the enclosing function returns it or hands it to someone else. The Swift book is explicit that global functions, nested functions and closure expressions are all closures: - a **global function** has a name and captures nothing; - a **nested function** has a name and can capture values from its enclosing function; - a **closure expression** has no name and captures from its surrounding context. So a nested function returned as `(Int) -> Bool` is the same kind of value as a closure expression of that type. The caller cannot tell them apart. ## What it captures A nested function can use any **parameter** of its enclosing function and any **constant or variable** declared there. Only what it actually uses is captured. Swift captures a variable **by reference**: the nested function and the enclosing body see the same storage, and that storage stays alive as long as the nested function does, even after the enclosing call has returned. As an optimisation, the Swift book notes, the compiler may store a copy instead when the value is mutated neither by the closure nor after the closure is created; the program cannot tell the difference. A retry helper shows why this matters: ```swift func makeRetryPolicy(maxAttempts: Int) -> (Int) -> Bool { var attemptsSeen = 0 func shouldRetry(statusCode: Int) -> Bool { attemptsSeen += 1 return statusCode >= 500 && attemptsSeen < maxAttempts } return shouldRetry } ``` The factory's frame is gone after it returns, but `attemptsSeen` and `maxAttempts` are not: they live on in the returned function. ## Who shares the captured state | Situation | Captured `attemptsSeen` | |---|---| | Two calls of `makeRetryPolicy` | Two independent variables, one per call | | One returned function assigned to a second constant | One variable, shared by both names | | A struct holding the returned function, then copied | One variable, shared by both copies | The last two rows follow from **functions being reference types**: assigning a function value copies a reference to the same closure, not the closure's state. A `let` holding the function freezes which function it refers to, not the variables that function captured. ## Tracing the example Run the code example's sequence step by step, with `maxAttempts` of 3 and a 503 status every time: 1. `checkout(503)` raises its counter to 1; 1 is below 3, so it returns `true`. 2. `alias(503)` is the same closure, so the same counter goes to 2 and the result is `true`. 3. `checkout(503)` takes the counter to 3; 3 is not below 3, so it returns `false`. 4. `profile(503)` came from a separate factory call, so its own counter goes from 0 to 1 and it returns `true`. A reviewer who expects four `true` results has assumed each name owns its state; one who expects `profile` to return `false` has assumed the factory's locals are shared between calls. ## Rules the compiler enforces 1. **No use before declaration.** A nested function may refer to a local declared later in the body, but calling it (or otherwise capturing it) before that line fails with "closure captures 'limit' before it is declared". 2. **No escaping `inout` capture.** A nested function may capture an `inout` parameter only while it cannot escape. Returning it, or assigning it to a variable, fails with "escaping local function captures 'inout' parameter 'x'", because an `inout` argument is only valid for the duration of the call. 3. **No capture list.** A nested function has no syntax for a capture list. If you need to copy a value at creation or hold a reference weakly, use a closure expression, which the material on capture lists and escaping covers. ## When a nested function beats a closure expression A nested function earns its place when the helper is more than a one-liner: - It has a **name**, so it can call itself recursively without the declare-then-assign workaround a closure needs; a closure expression that refers to its own constant fails with an error such as "use of local variable 'h' before its declaration". - It can have **argument labels and default values**, which a closure expression cannot declare. - It can be **generic**, as in `func describe<T>(_ value: T) -> String` inside another function. A closure expression wins when the code is short and passed inline, or when it needs a capture list.
- Can a nested function capture an inout parameter at all?Yes, as long as it does not escape. Calling it inside the enclosing function is fine, and it modifies the caller's variable through the `inout` binding. Returning it or storing it in a variable fails with "escaping local function captures 'inout' parameter", since the `inout` access ends when the enclosing call returns. Copy the value into a local first if the function must outlive the call.
- Why is the nested retry function's counter not reset between calls of the returned function?`attemptsSeen` is declared in the factory, not in `shouldRetry`, so it is created once per factory call and captured by reference. Each call of the returned function increments the same variable. To reset per request, call the factory again, or declare the counter inside the nested function if it should not persist.
- A returned nested function gets a snapshot of the locals, so its updates are lost.
- Every call of the factory shares one counter, since the variable is declared once in source.
- Nested functions cannot capture the enclosing function's parameters, only its locals.
- Assigning a returned function to another constant copies its captured state.
- A nested function can declare a capture list just like a closure expression.