← Back to Swift Course | Chapter 7: Closures | Lesson 5 of 6

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
swift
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

markup
// 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")

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

markup
// 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")
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
  1. Overusing @autoclosure for regular parameters; it's meant for delaying evaluation of an expression, not as a general-purpose convenience.
  2. Forgetting that an @autoclosure parameter is called like a normal expression at the call site, not with explicit closure braces.
  3. 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
  • @autoclosure automatically 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 assert and ?? use autoclosures internally for lazy evaluation.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.