In Swift, when does a defer block run, and in what order do several defer blocks in the same scope execute?
answer
- the nearest enclosing braces
- registered only when reached
- last written runs first
- return value computed before cleanup
- await allowed since 6.4
basics
~20 sA defer block runs when control leaves the scope it was declared in, by return, break, continue, a thrown error or reaching the closing brace. Several defer blocks in one scope run in reverse order: the last one written runs first.
solid answer
~50 s`defer { ... }` schedules code for the moment control leaves the **enclosing scope** - the nearest braces, not necessarily the function - however it leaves: `return`, `break`, `continue`, a thrown error, or falling off the end. Only `defer` statements that execution actually reached are registered, so one written after an early `return` does not run on that return. Multiple `defer` blocks in one scope run last-in, first-out, which lets a later cleanup still use what an earlier one will tear down; a `defer` inside a loop body runs at the end of every pass. A `return` expression is evaluated before the `defer` blocks run, so mutating a returned local in a `defer` does not change the value returned. A `defer` body cannot `return`, `break` or throw out of itself. Since Swift 6.4 (SE-0493), a `defer` inside an `async` context may `await`, and scope exit implicitly waits for it.
code
swift · 21 linesfunc importBatch(_ rows: [Int]) -> Int {
print("open file")
defer { print("close file") }
print("begin transaction")
defer { print("end transaction") }
guard !rows.isEmpty else {
print("nothing to import")
return 0
}
defer { print("log row count") }
for row in rows {
defer { print(" row \(row) done") }
if row < 0 { continue }
print(" insert \(row)")
}
return rows.count
}
_ = importBatch([])
print("---")
_ = importBatch([1, -2])go deeper
Recall that defer runs when its scope ends, on every normal exit, and that several defers run last-written first.
Explain scope-level timing with a defer in a loop or if block, why an unreached defer never runs, and why the return value is fixed before defer runs.
Use defer for paired setup and teardown in production code, know it does not run on a trap, and handle cleanup errors inside the block since nothing can be thrown out.
Weigh adopting Swift 6.4 async defer against the unstructured Task workarounds already in a codebase, given the toolchain versions the team must still support.
## What `defer` does A `defer` statement holds a block of code that Swift runs **just before control leaves the scope the `defer` appears in**. It exists so that cleanup - closing a file, ending a transaction, releasing a lock, restoring a flag - sits next to the setup it undoes, instead of being repeated on every exit path. ```swift func importBatch(_ rows: [Int]) -> Int { print("open file") defer { print("close file") } print("begin transaction") defer { print("end transaction") } // ... work with several exits ... } ``` ## When the block runs The reference manual says the statements in a `defer` run no matter how program control is transferred. The ways out of a scope are: 1. Reaching the closing brace normally. 2. `return` from the function, closure or getter. 3. `break` or `continue`, when the `defer` is inside a loop body or a `switch` case. 4. An error being thrown out of the scope (how errors propagate is covered in the Swift lesson on throwing and catching). Three precise points sit on top of that list: - **Scope means the nearest braces.** A `defer` inside an `if` block runs when that block ends; one inside a loop body runs at the end of **every pass**, including a pass cut short by `continue`. - **Only reached `defer` statements count.** A `defer` registers when execution passes it. If the function returns before reaching line 3, the `defer` on line 3 never runs. - **A trap is not an exit.** When the process stops - `fatalError(_:)`, a failed precondition, an out-of-bounds subscript - no `defer` block runs. ## Reverse order and nested scopes Within one scope, `defer` blocks run in the **reverse** of the order they were written. The reference manual gives the reason: the last `defer` runs first, so it can still refer to resources that earlier `defer` blocks will clean up. Nested scopes finish first, so an inner block's `defer` runs before an outer one's. | Call | Printed sequence | |---|---| | `importBatch([])` | open file, begin transaction, nothing to import, end transaction, close file | | `importBatch([1, -2])` | open file, begin transaction, insert 1, row 1 done, row -2 done, log row count, end transaction, close file | In the empty case, the `defer` that logs the row count is written after the `guard` and is never reached, so it never runs. ## The return value is computed first A `return` statement evaluates its expression **before** the `defer` blocks run: ```swift func counter() -> Int { var n = 1 defer { n += 1 } return n // returns 1; n becomes 2 afterwards } ``` The value 1 is already the result when the `defer` increments the local. This matters when a `defer` resets state the caller reads, and is a favourite interview trap. ## What a `defer` body may not do The compiler keeps `defer` a pure cleanup step: - It cannot transfer control out: `return` or `break` inside it fails with "'return' cannot transfer control out of a defer statement" (the message names whichever statement was used). - It cannot throw out: "errors cannot be thrown out of a defer body". Cleanup that can fail must handle its error inside the block. - A `defer` that is the last statement of its scope runs immediately, so the compiler warns: "'defer' statement at end of scope always executes immediately; replace with 'do' statement to silence this warning". ## `await` in `defer` (Swift 6.4) Before Swift 6.4, a `defer` body could not call an `async` function, which pushed asynchronous cleanup into an unstructured `Task` that might run later. **SE-0493, implemented in Swift 6.4**, allows `await` inside a `defer` whenever the enclosing context is already `async`: ```swift func upload(_ ok: Bool) async throws { let connection = Connection() // an actor defer { await connection.close() } // Swift 6.4 or later if !ok { throw UploadFailed() } } ``` The rules carry over unchanged: reverse order, every exit path, and the scope waits for an asynchronous `defer` to finish before control leaves, so the function does not return until `close()` completes. The `defer` body keeps the isolation of its enclosing scope. In a synchronous function, the compiler rejects it with "'async' defer must appear within an 'async' context". (Tasks, actors and isolation are covered in the Swift lessons on concurrency.)
- Does a defer block run if the function calls fatalError after it?No. `fatalError(_:)` stops the process instead of leaving the scope, so no `defer` block runs. `defer` covers the normal exits - closing brace, `return`, `break`, `continue` and thrown errors - not traps.
- What does the Swift compiler say about a defer written as the last statement of its scope?It warns: "'defer' statement at end of scope always executes immediately; replace with 'do' statement to silence this warning". Nothing follows the `defer`, so deferring buys nothing; the block runs at once. The usual cause is a `defer` placed after the work it was meant to protect instead of right after the setup.
- Before Swift 6.4, how did code perform async cleanup on scope exit?It could not await in a `defer`, so teams either repeated the awaited cleanup on every exit path or started an unstructured `Task` inside the `defer`, which runs at some later point and lets the function return before cleanup finishes. Swift 6.4's SE-0493 removes the need for both workarounds in async contexts.
Like sticking reminder notes on the door as you set things up: close the file, then end the transaction on top of it. When you leave, you act on the top note first. A note you never wrote, because you left early, is never acted on.
- defer always runs when the function ends, whatever scope it is declared in
- Several defer blocks run in the order they are written
- A defer declared after an early return still runs on that return
- Incrementing a returned local inside defer changes the returned value
- A defer body can throw to report that cleanup failed
- Async functions have always been able to await inside defer
Assumes Swift 6.4: await inside a defer body is accepted from Swift 6.4 (SE-0493) and rejected by earlier compilers; the ordering and exit rules are the same in every supported release.