← 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.

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
func logIfTrue(_ condition: @autoclosure () -> Bool, message: String) {
    if condition() {
        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
func describe(_ value: @autoclosure () -> String) {
    print("Describing: \(value())")
}
describe("a lazily evaluated string")
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.