Challenge - 5 Problems
Autoclosure Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this Swift code using @autoclosure?
Consider the following Swift code snippet. What will be printed when it runs?
Swift
func logIfTrue(_ predicate: @autoclosure () -> Bool) { if predicate() { print("It's true!") } else { print("It's false!") } } logIfTrue(2 > 1)
Attempts:
2 left
💡 Hint
Remember that @autoclosure delays evaluation until the function uses the predicate.
✗ Incorrect
The @autoclosure attribute wraps the expression '2 > 1' so it is only evaluated when predicate() is called. Since 2 > 1 is true, the function prints "It's true!".
🧠 Conceptual
intermediate1:30remaining
What is the main benefit of using @autoclosure in Swift?
Why would a Swift programmer use the @autoclosure attribute on a function parameter?
Attempts:
2 left
💡 Hint
Think about when the expression inside the function is actually run.
✗ Incorrect
Using @autoclosure delays the evaluation of the passed expression until the function explicitly calls it, which can improve readability and performance by avoiding unnecessary computation.
🔧 Debug
advanced2:30remaining
Why does this Swift code cause a compile error?
Examine the code below. Why does it fail to compile?
Swift
func check(_ condition: @autoclosure () -> Bool) { if condition { print("True") } else { print("False") } } check(5 > 3)
Attempts:
2 left
💡 Hint
How do you use a closure parameter inside a function?
✗ Incorrect
The parameter 'condition' is a closure due to @autoclosure, so it must be called with parentheses 'condition()' to get the Bool value. Using 'if condition' causes a type mismatch error.
📝 Syntax
advanced2:00remaining
Which option correctly declares a function with an @autoclosure parameter that can escape?
Select the correct Swift function declaration that uses @autoclosure and allows the closure to escape the function body.
Attempts:
2 left
💡 Hint
Remember the order of attributes matters in Swift.
✗ Incorrect
The correct syntax places @autoclosure before @escaping: '@autoclosure @escaping () -> Bool'. Option B is correct. Option B reverses the order which is invalid. Option B is invalid syntax. Option B lacks @escaping.
🚀 Application
expert2:30remaining
How many times is the expression evaluated in this Swift code?
Given the code below, how many times will the expression 'print("Evaluated") ; return true' be executed?
Swift
func test(_ condition: @autoclosure () -> Bool) { if condition() { print("First check passed") } if condition() { print("Second check passed") } } test(print("Evaluated"); return true)
Attempts:
2 left
💡 Hint
Think about when the closure is called and how many times.
✗ Incorrect
The @autoclosure wraps the expression, but each call to condition() evaluates it again. Since condition() is called twice, the expression runs twice, printing "Evaluated" two times.