Autoclosures
An autoclosure is a sneaky little wrapper Swift adds automatically around an expression, so it isn't actually computed until you decide to use it.
Syntax
func functionName(_ condition: @autoclosure () -> Type) {
condition() // expression evaluated only here
}
functionName(expression) // no braces needed
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
// Define the function `logIfTrue` taking `condition`, `message`
func logIfTrue(_ condition: @autoclosure () -> Bool, message: String) {
// Check whether `condition()`
if condition() {
// Print `message` to the console
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
// Define the function `describe` taking `value`
func describe(_ value: @autoclosure () -> String) {
// Print "Describing: \(value())" to the console
print("Describing: \(value())")
}
describe("a lazily evaluated string")
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- 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.
Chapter Summary
@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: