0
0
Swiftprogramming~10 mins

Escaping closures (@escaping) in Swift - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete 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'
A@discardableResult
B@escaping
C@autoclosure
D@inline
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.
2fill in blank
medium

Complete 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'
A@autoclosure
B@inline
C@discardableResult
D@escaping
Attempts:
3 left
💡 Hint
Common Mistakes
Not marking the closure as @escaping causes a compile error.
Confusing @escaping with other closure attributes.
3fill in blank
hard

Fix 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'
A@escaping
B@autoclosure
C@discardableResult
D@inline
Attempts:
3 left
💡 Hint
Common Mistakes
Omitting @escaping causes a compile-time error.
Using @autoclosure instead of @escaping.
4fill in blank
hard

Fill 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'
A@escaping
Basync
Cawait
D@autoclosure
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting @escaping on the closure parameter.
Using 'await' instead of 'async' in DispatchQueue.
5fill in blank
hard

Fill 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'
A@escaping
Basync
C.
D?
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.