0Pricing
Swift Academy · Lesson

Autoclosures

Delay expression evaluation with @autoclosure.

Autoclosures is a free Swift Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

What Is an Autoclosure?

@autoclosure automatically wraps an argument expression in a closure, so it is not evaluated until the function actually uses it. The caller writes a plain expression, not a closure.

Without Autoclosure

Normally delayed evaluation needs an explicit closure at the call site:

func logIf(_ cond: Bool, _ message: () -> String) {
    if cond { print(message()) }
}
logIf(true) { "expensive" }  // caller writes braces

With Autoclosure

@autoclosure lets the caller pass a bare expression:

func logIf(_ cond: Bool, _ message: @autoclosure () -> String) {
    if cond { print(message()) }
}
logIf(true, "expensive")  // no braces, evaluated only if cond

Deferred Evaluation Proof

The expression runs only when the closure is invoked:

func pick(_ cond: Bool, _ value: @autoclosure () -> Int) -> Int {
    cond ? value() : -1
}
func costly() -> Int { print("computed"); return 42 }
print(pick(false, costly()))  // -1  -- "computed" never prints

Where the Standard Library Uses It

The && and || operators, assert, and ?? all use autoclosures so the right-hand side is evaluated only when needed.

Short-Circuit Like ??

A custom default-value function that skips the fallback when not needed:

func orElse<T>(_ value: T?, _ fallback: @autoclosure () -> T) -> T {
    value ?? fallback()
}
func makeDefault() -> Int { print("built"); return 0 }
print(orElse(5, makeDefault()))  // 5  -- "built" never prints

Lazy assert-Style Messages

Build the message only when the check fails:

func check(_ cond: Bool, _ msg: @autoclosure () -> String) {
    if !cond { print("FAIL: \(msg())") }
}
check(true, "this is never built")
check(false, "boom")  // FAIL: boom

Autoclosure plus Escaping

Combine with @escaping to store the deferred expression for later:

var thunks: [() -> Int] = []
func defer2(_ expr: @autoclosure @escaping () -> Int) {
    thunks.append(expr)
}
defer2(1 + 1)
print(thunks[0]())  // 2  -- computed on demand

Reading Cleaner at the Call Site

The win is purely syntactic: callers write a value, the function gets a closure:

func unless(_ cond: Bool, _ value: @autoclosure () -> String) -> String {
    cond ? "skipped" : value()
}
print(unless(false, "shown"))  // "shown"

When NOT to Use It

Autoclosures hide that an argument is a closure, which can surprise readers. Use them sparingly — only when delayed evaluation genuinely helps, like avoiding expensive defaults.

func first<T>(_ a: T?, _ b: @autoclosure () -> T) -> T { a ?? b() }
print(first(nil, 99))  // 99

Autoclosures Take No Arguments

An autoclosure always has the form () -> T — it wraps a single expression and cannot take parameters:

func once(_ make: @autoclosure () -> [Int]) -> Int {
    make().count
}
print(once([1, 2, 3]))  // 3

Quick Check

What does @autoclosure do to its argument?

Recap

You learned autoclosures:

  • @autoclosure wraps an argument expression in a () -> T closure
  • The expression runs only when the function calls it — delayed evaluation
  • Powers &&, ||, ??, and assert
  • Combine with @escaping to store; use sparingly for clarity

Course complete! Next: Equatable, Hashable, Comparable.

Frequently asked questions

Is the “Autoclosures” lesson free?

Yes — the full text of “Autoclosures” is free to read here on the web, and the Swift Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Swift Academy course, upgrade to CoddyKit PRO.

What will I learn in “Autoclosures”?

Delay expression evaluation with @autoclosure. You practise Swift Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Swift Academy?

No prior experience is required. Swift Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Autoclosures” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Swift Academy lesson?

Yes. Every Swift Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Capturing Values by Reference
  2. Escaping Closures
  3. Capture Lists and Weak Self
  4. Autoclosures
← Back to Swift Academy