tezvyn:

What is @autoclosure and when is it useful?

AI-drafted, machine-checkedSource: interviewadvanced
WHAT IT TESTS

understanding deferred, lazy evaluation.

OUTLINE

@autoclosure wraps an argument expression in a closure so it evaluates lazily only if used, enabling clean APIs like assert and the ?? operator.

WHAT THIS TESTS This checks deep language knowledge: do you understand that arguments are normally evaluated eagerly, and that @autoclosure changes that contract by deferring evaluation? It also tests judgment, because the feature trades performance and expressiveness for reduced transparency.

A GOOD ANSWER COVERS Normally Swift evaluates a function argument before the call. Marking a parameter @autoclosure tells the compiler to automatically wrap the argument expression in a zero-argument closure, so the expression runs only when the function body actually calls that closure. This enables APIs where the work should be skipped if unnecessary. The standard library uses it for assert(_:_:), where the message and condition are not computed in release builds, and for the ?? operator, where the right-hand default is evaluated only when the left side is nil. Combine it with @escaping when the closure must outlive the call, for example to log lazily.

COMMON WRONG ANSWERS Describing it as just shorthand for passing a closure with empty braces. Ignoring the trade-off and recommending it broadly. Forgetting that callers can no longer tell the argument is deferred, so side effects may run later or never.

LIKELY FOLLOW-UPS How does @autoclosure interact with @escaping? Why is it dangerous when the expression has side effects? How does the ?? operator use it? What is the performance benefit in assert?

ONE CONCRETE EXAMPLE Consider func logIfEnabled(_ message: @autoclosure () -> String). Calling logIfEnabled(expensiveDescription()) does not run expensiveDescription unless logging is enabled, because the function decides whether to invoke the closure. Without @autoclosure the caller would have to write { expensiveDescription() }, and without lazy evaluation the expensive call would always run even when its result is discarded.

Read the original → docs.swift.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.