@autoclosure

Swift language Mid-level Swift 5.0+ iOS 17+ Reviewed By Alok Singh

Predict the output

What does this print?

func log(_ message: @autoclosure () -> String, enabled: Bool) {
    if enabled { print(message()) }
}
func expensive() -> String {
    print("computing")
    return "msg"
}
log(expensive(), enabled: false)
log(expensive(), enabled: true)
Options
Hint 1 of 1

When does an autoclosure run?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: B computing, msg

Correct. Only the second call evaluates the message.

Why not the others?
  • A computing, computing, msg. With enabled false, the closure is never called, so expensive() doesn't run.
  • C msg. Calling the closure runs expensive(), which prints first.
  • D Nothing. The second call is enabled.

30-second answer

@autoclosure wraps an argument expression in a closure automatically, so the caller writes a normal expression but it is evaluated only if and when the function calls it. It enables lazy evaluation, as in assert, ?? and &&. Use it sparingly, because callers can't see that evaluation is delayed.

Practise saying it · 30 s. No recording, just a timer

Explain @autoclosure.

Say your answer out loud, then check which of these points you covered:

  • Wraps an expression in a closure
  • Evaluated only if called
  • Use sparingly

Deep dive

??'s right-hand side is an autoclosure, so it is evaluated only when needed.

Combine with @escaping if the closure is stored.

Good for logging and assertions where building the message is expensive.

Avoid it when side effects in the argument matter to the reader.

Common mistakes

  • Hiding side effects behind autoclosure.
  • Using it to save typing braces.

Senior take & follow-ups

Seniors cite standard-library examples and the readability trade-off.

Follow-up questions

Think of your answer first, then open the hint.

  1. Why is ?? an autoclosure?

    Show hint

    So the default is only computed when needed.

  2. Can an autoclosure escape?

    Show hint

    Yes, with @autoclosure @escaping.

Suggest a fix if something here is wrong or out of date.