Junior — Middle
Can you explain what is meant by Auto Closure in programming?
sobes.tech AI
Answer from AI
Auto Closure is a mechanism in Swift that automatically wraps an expression into a closure. This means that instead of passing a closure explicitly, you can pass an expression that will be evaluated only when the closure is called.
Advantages:
- Deferred evaluation: the expression is not computed immediately, but only when needed.
- Syntactic convenience: code becomes cleaner and simpler.
Example:
func logIfTrue(_ predicate: @autoclosure () -> Bool) {
if predicate() {
print("Condition is true")
}
}
logIfTrue(2 > 1) // The expression 2 > 1 is automatically wrapped into a closure
Here, 2 > 1 is not evaluated immediately when calling, but only inside the function when predicate() is called.