0
0
Swiftprogramming~5 mins

Autoclosures (@autoclosure) in Swift - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is an @autoclosure in Swift?
An @autoclosure automatically wraps an expression in a closure, delaying its evaluation until it's called. It lets you write cleaner code by avoiding explicit closure syntax.
Click to reveal answer
beginner
How does @autoclosure improve function call syntax?
It lets you pass an expression directly instead of a closure, making the call look simpler and more natural, while still delaying evaluation.
Click to reveal answer
intermediate
Example: What does this function signature mean?<br>
func logIfTrue(_ predicate: @autoclosure () -> Bool)
It means you can pass a Boolean expression directly to logIfTrue, and the expression will only be evaluated inside the function when needed.
Click to reveal answer
intermediate
Why use @autoclosure instead of a normal closure?
Because it makes the call site cleaner and easier to read by letting you write expressions directly, without extra braces or { } syntax.
Click to reveal answer
advanced
Can @autoclosure be combined with @escaping? What does that mean?
Yes, combining @autoclosure with @escaping means the delayed expression can be stored and called later, not just during the function call.
Click to reveal answer
What does @autoclosure do in Swift?
AAutomatically wraps an expression in a closure delaying its evaluation
BImmediately executes a closure
CConverts a closure to a function
DPrevents a closure from capturing variables
Which is a benefit of using @autoclosure?
APrevents functions from returning values
BForces immediate evaluation of expressions
CAutomatically unwraps optionals
DSimplifies function call syntax by allowing expressions instead of closures
How do you declare a function parameter as an autoclosure?
AUse <code>inout</code> keyword
BUse <code>@autoclosure</code> before the parameter type
CUse <code>lazy</code> keyword
DUse <code>@escaping</code> before the parameter type
What happens if you combine @autoclosure with @escaping?
AThe closure can be stored and called later, not just immediately
BThe closure runs immediately
CThe closure cannot capture variables
DThe closure is converted to a synchronous function
Which of these is a correct use of @autoclosure?
Afunc check(_ condition: () -> Bool) { if condition { print("True") } }
Bfunc check(_ condition: Bool) { if condition { print("True") } }
Cfunc check(_ condition: @autoclosure () -> Bool) { if condition() { print("True") } }
Dfunc check(_ condition: @escaping Bool) { if condition { print("True") } }
Explain what @autoclosure does and why it is useful in Swift.
Think about how it changes the way you write function arguments.
You got /4 concepts.
    Describe a situation where combining @autoclosure with @escaping would be helpful.
    Consider when you want to save a condition to check later.
    You got /4 concepts.