Autoclosures
Declaring an Autoclosure Parameter
Marking a parameter @autoclosure lets callers pass a plain expression, which Swift automatically wraps into a closure that's only evaluated when used inside the function.
Example: Declaring an Autoclosure Parameter
func logIfTrue(_ condition: @autoclosure () -> Bool, message: String) {
if condition() {
print(message)
}
}
logIfTrue(5 > 3, message: "Five is greater than three")
Login to try C/C++/Java/PHP code in the editor
Why Autoclosures Delay Evaluation
Because the expression is wrapped in a closure, it is only evaluated when the closure is actually called inside the function, which can avoid unnecessary work.
Note: This is exactly how ?? avoids evaluating its right-hand side unless the left side is nil.
Example: Why Autoclosures Delay Evaluation
func describe(_ value: @autoclosure () -> String) {
print("Describing: \(value())")
}
describe("a lazily evaluated string")
Login to try C/C++/Java/PHP code in the editor
- Overusing
@autoclosurefor regular parameters; it's meant for delaying evaluation of an expression, not as a general-purpose convenience. - Forgetting that an
@autoclosureparameter is called like a normal expression at the call site, not with explicit closure braces. - Not realizing the whole point of autoclosures is lazy evaluation -- if used carelessly, side effects inside the expression might not run when expected.
@autoclosureautomatically wraps a plain expression argument into a closure.- This delays the expression's evaluation until the closure is actually called inside the function.
- It lets call sites look like a normal expression instead of requiring explicit closure braces.
- Swift's built-in
assertand??use autoclosures internally for lazy evaluation.
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: