Challenge - 5 Problems
Escaping Closure Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of a function with an escaping closure
What will be printed when this Swift code runs?
Swift
func performTask(completion: @escaping () -> Void) { DispatchQueue.global().async { print("Task started") completion() } } performTask { print("Task completed") } print("Function called")
Attempts:
2 left
💡 Hint
Think about how async code runs in the background and when the print statements execute.
✗ Incorrect
The function performTask starts an asynchronous task. The print("Function called") runs immediately after calling performTask, before the async block executes. So the output order is: Function called, then Task started, then Task completed.
🧠 Conceptual
intermediate1:30remaining
Why use @escaping in Swift closures?
Which statement best explains why the @escaping attribute is required for a closure parameter in Swift?
Attempts:
2 left
💡 Hint
Think about when the closure is executed relative to the function call.
✗ Incorrect
The @escaping attribute is needed when the closure is stored or called after the function returns, meaning it escapes the function's lifetime.
🔧 Debug
advanced2:00remaining
Identify the error with closure escaping
What error will this Swift code produce and why?
Swift
func fetchData(completion: () -> Void) { DispatchQueue.global().async { completion() } } fetchData { print("Data fetched") }
Attempts:
2 left
💡 Hint
Check the closure parameter declaration and how it's used inside an async block.
✗ Incorrect
The closure parameter is non-escaping by default. Using it inside an async block means it escapes the function scope, causing a compile-time error.
📝 Syntax
advanced1:30remaining
Correct syntax for an escaping closure parameter
Which option correctly declares a function with an escaping closure parameter in Swift?
Attempts:
2 left
💡 Hint
Remember the position of @escaping in the parameter declaration.
✗ Incorrect
The @escaping attribute must appear before the closure type in the parameter declaration.
🚀 Application
expert2:30remaining
Determine the final value after escaping closure modifies a variable
What is the value of 'counter' after this Swift code runs?
Swift
var counter = 0 func incrementLater(completion: @escaping () -> Void) { DispatchQueue.global().async { counter += 1 completion() } } incrementLater { print("Increment done") } // Wait briefly to let async code finish Thread.sleep(forTimeInterval: 0.1) print(counter)
Attempts:
2 left
💡 Hint
Consider that the increment happens asynchronously and the main thread waits before printing.
✗ Incorrect
The async block increments counter by 1. The main thread waits briefly to let the async code finish, so counter is 1 when printed.