Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare a function parameter as an escaping closure.
Swift
func performTask(completion: [1] () -> Void) {
// function body
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to add @escaping causes a compile error when the closure is used asynchronously.
Using @autoclosure instead of @escaping.
✗ Incorrect
The @escaping keyword is used to mark a closure parameter that can escape the function's scope.
2fill in blank
mediumComplete the code to store an escaping closure in a property.
Swift
class Handler { var completionHandler: (() -> Void)? func setHandler(handler: [1] () -> Void) { completionHandler = handler } }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Not marking the closure as @escaping causes a compile error.
Confusing @escaping with other closure attributes.
✗ Incorrect
The closure parameter must be marked @escaping because it is stored beyond the function's lifetime.
3fill in blank
hardFix the error in the function declaration by marking the closure parameter correctly.
Swift
func fetchData(completion: [1] () -> Void) {
DispatchQueue.global().async {
// some async work
completion()
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Omitting @escaping causes a compile-time error.
Using @autoclosure instead of @escaping.
✗ Incorrect
The closure is called asynchronously, so it must be marked @escaping.
4fill in blank
hardFill both blanks to declare a function with an escaping closure and call it asynchronously.
Swift
func executeTask(task: [1] () -> Void) { DispatchQueue.main.[2] { task() } }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting @escaping on the closure parameter.
Using 'await' instead of 'async' in DispatchQueue.
✗ Incorrect
The closure parameter must be marked @escaping because it is called asynchronously. The DispatchQueue method uses async to schedule the closure.
5fill in blank
hardFill all three blanks to declare a class with an escaping closure property, a method to set it, and a method to call it.
Swift
class AsyncProcessor { var completion: (() -> Void)? func setCompletion(handler: [1] () -> Void) { completion = handler } func run() { DispatchQueue.global().[2] { // do work self.completion[3]() } } }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Not marking the closure as @escaping.
Forgetting to use optional chaining when calling the closure.
Using '.' instead of '?' for optional closure call.
✗ Incorrect
The closure parameter must be @escaping because it is stored. The async keyword is used for asynchronous dispatch. The optional chaining operator '?' safely calls the closure if it exists.