In Swift, how does @autoclosure let ?? and assert(_:_:file:line:) skip evaluating an argument, and what makes it risky in your own APIs?
answer
- an expression without braces
- runs only when called
- short-circuit operators
- debug-only assert condition
- laziness hidden at the call site
basics
~20 s@autoclosure wraps the argument expression in a parameterless closure, so the callee decides whether and when it runs: ?? evaluates its default only when the optional is nil, and assert evaluates its condition only in -Onone builds and playgrounds. Callers cannot see that deferral.
solid answer
~50 sA parameter of type `@autoclosure () -> T` accepts an ordinary expression; Swift wraps it in a closure with no arguments, and the expression runs only when the function calls that closure. The standard library uses this for short-circuiting: `??` declares `defaultValue: @autoclosure () throws -> T`, so `cache ?? loadFromDisk()` calls `loadFromDisk()` only on `nil`, and `&&` and `||` take their right side the same way. `assert(_:_:file:line:)` takes its condition and message as autoclosures and evaluates the condition only in `-Onone` builds and playgrounds. In your own APIs the risk is that the deferral is invisible: a reader of `debugLog("state " + describeCache())` cannot tell that `describeCache()` may never run, or may run more than once. Keep it for cases where the name makes deferral obvious, such as logging and assertions; the book itself warns that overusing autoclosures makes code hard to understand.
code
swift · 25 linesfinal class Diagnostics {
var isVerbose = false
var renders = 0
func describeCache() -> String {
renders += 1
return "cache: 120 entries"
}
func debugLog(_ message: @autoclosure () -> String) {
guard isVerbose else { return } // message() is never called on this path
print(message())
}
}
let diagnostics = Diagnostics()
diagnostics.debugLog("downloader state - " + diagnostics.describeCache())
print("renders after quiet log:", diagnostics.renders) // 0
diagnostics.isVerbose = true
diagnostics.debugLog("downloader state - " + diagnostics.describeCache())
print("renders after verbose log:", diagnostics.renders) // 1
let cachedPath: String? = nil
let path = cachedPath ?? diagnostics.describeCache() // right side runs: left is nil
print(path, diagnostics.renders) // cache: 120 entries 2go deeper
Recall that ?? only builds its default when the left side is nil, and that @autoclosure is the attribute that lets a plain expression be passed lazily.
Explain the parameter shape () -> T, how && and || short-circuit through it, and why assert conditions vanish from -O builds.
Spot autoclosure hazards in review: side effects in arguments, repeated evaluation, escaping autoclosures that capture self, and logic hidden in assert conditions.
Limit @autoclosure in shared APIs to logging, assertions and true short-circuit operators, and prefer explicit closures where callers must see that evaluation is deferred.
## What @autoclosure does An **autoclosure** is a closure Swift creates automatically around an argument expression. You mark a parameter whose type is a function **taking no arguments**, `@autoclosure () -> T`, and callers pass a plain expression of type `T`: ```swift func debugLog(_ message: @autoclosure () -> String) { guard isVerbose else { return } print(message()) } debugLog("downloader state - " + describeCache()) ``` The expression is **not evaluated at the call**. It runs each time the function calls `message()` — possibly never, possibly more than once. There is no caching: an autoclosure called twice evaluates its expression twice. ## Where the standard library relies on it | API | Autoclosure parameter | When it is evaluated | |---|---|---| | `??` | `defaultValue: @autoclosure () throws -> T` | only if the left side is `nil` | | `&&` | `rhs: @autoclosure () throws -> Bool` | only if the left side is `true` | | `\|\|` | `rhs: @autoclosure () throws -> Bool` | only if the left side is `false` | | `assert(_:_:file:line:)` | condition and message | condition only in `-Onone` builds and playgrounds; message only on failure | | `precondition(_:_:file:line:)` | condition and message | condition in `-Onone` and `-O` builds | This is how ordinary functions implement **short-circuit evaluation**. The `??` doc comment states it directly: the optional is checked first, and `defaultValue` is evaluated only if the optional is `nil`. For `assert`, the standard library documents that in `-O` builds (the default for a Release configuration) the condition is not evaluated and there are no effects — so an `assert` whose condition has a side effect behaves differently between Debug and Release. ## The rules the compiler enforces 1. The parameter must be a function type with **no arguments**; `@autoclosure (Int) -> Bool` is rejected with `argument type of '@autoclosure' parameter must be '()'`. 2. `@autoclosure` applies only to function types; `@autoclosure String` is rejected with `'@autoclosure' only applies to function types`. 3. An autoclosure parameter is **non-escaping** like any other closure parameter. To store it, write `@autoclosure @escaping () -> String`. 4. You cannot pass an existing closure value, or forward one autoclosure parameter, as the argument. The compiler says `add () to forward '@autoclosure' parameter`; writing `debugLog(message())` creates a new autoclosure around the call, so evaluation stays deferred. 5. The wrapped expression may throw if the parameter type is `throws`, which is how `??` and `&&` are declared with `rethrows`. ## Risks in your own APIs - **Hidden laziness.** The call site looks like an eager value. A side effect in the argument — removing an element, incrementing a counter — silently depends on the callee's internal branches. - **Repeated evaluation.** If the callee calls the closure in a loop or twice, an expensive or side-effecting expression runs repeatedly. - **Extended lifetimes.** With `@escaping`, the stored autoclosure captures everything the expression mentions, including `self`, without any braces to remind the caller. - **Build-configuration drift.** Logic placed in an `assert` condition disappears from Release builds. The Swift book's own guidance is that overusing autoclosures makes code hard to understand, and that the context and function name should make clear that evaluation is being deferred. ## When it earns its place - Logging and diagnostics whose messages are costly to build and usually discarded. - Assertion-like helpers where skipping the check is the point. - Custom operators that genuinely short-circuit, following `&&`, `||` and `??`. Anywhere else, an explicit closure parameter — `debugLog { "state " + describeCache() }` — shows the deferral in the braces and costs one pair of characters. ## Autoclosure or explicit closure? | Question | `@autoclosure` | explicit closure parameter | |---|---|---| | Does the call site show deferral? | no — it looks like a value | yes — the braces show it | | Can the closure take arguments? | no, always `()` | yes | | Typical use | `??`, `&&`, `\|\|`, `assert`, logging | callbacks, transforms, completion handlers | A useful review test: if a reader could reasonably assume the argument is evaluated exactly once before the call, and the function breaks that assumption, the parameter should be an explicit closure.
- In Swift, how do you pass an @autoclosure parameter on to another function that also takes an @autoclosure?Call it: `debugLog(message())`. Passing `message` itself fails with `add () to forward '@autoclosure' parameter`. The call expression is wrapped in a new autoclosure by the receiving function, so `message()` still runs only if and when that function evaluates its argument.
- In Swift, when does an @autoclosure parameter also need @escaping?When the function stores it or calls it after returning, for example queuing log messages to format later. The declaration becomes `@autoclosure @escaping () -> String`; without `@escaping`, storing it is rejected like any non-escaping closure.
- In Swift, why is `assert(cache.removeExpired() > 0)` a bug in Release builds?`assert(_:_:file:line:)` evaluates its condition only in `-Onone` builds and playgrounds. In an `-O` Release build the autoclosure is never called, so `removeExpired()` never runs and the cache keeps its expired entries. Do the work first, then assert on the result.
- @autoclosure caches the result after the first evaluation.
- assert evaluates its condition in Release builds and only skips the message.
- An @autoclosure parameter can take arguments, such as (Int) -> Bool.
- ?? evaluates both sides and then returns the non-nil one.
- An existing closure value can be passed straight to an @autoclosure parameter.