What if your app could remember to finish tasks even after the function is gone? That's the magic of escaping closures!
Why Escaping closures (@escaping) in Swift? - Purpose & Use Cases
Imagine you want to run some code later, like after downloading a photo from the internet. You try to write that code inside a function, but the function ends before the download finishes.
Without a way to keep that code alive, your program forgets what to do next. This makes your app stop or crash because it tries to use something that no longer exists.
Escaping closures let you tell Swift: "Hey, keep this code safe and run it later, even after the function ends." This way, your app waits patiently and works smoothly.
func loadData(completion: () -> Void) {
// Can't run completion after function ends
}
loadData {
print("Done")
}func loadData(completion: @escaping () -> Void) {
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
completion()
}
}
loadData {
print("Done")
}It enables your app to handle tasks that finish later, like network calls or animations, without losing track of what to do next.
When you tap a button to fetch weather info, escaping closures let your app wait for the data and then update the screen once it arrives.
Without escaping closures, delayed code can't run properly.
@escaping tells Swift to keep the closure alive beyond the function.
This makes asynchronous tasks safe and smooth in your app.
Practice
@escaping keyword indicate in Swift closures?Solution
Step 1: Understand closure execution timing
Closures without@escapingrun inside the function before it returns.Step 2: Role of
Marking a closure@escaping@escapingmeans it can be stored and called later, after the function ends.Final Answer:
The closure can be called after the function returns -> Option AQuick Check:
@escapingmeans delayed closure call [OK]
- Thinking @escaping closures run immediately
- Confusing @escaping with synchronous execution
- Believing @escaping closures cannot capture variables
Solution
Step 1: Identify correct placement of @escaping
The@escapingkeyword must appear before the closure type in the parameter list.Step 2: Check each option's syntax
func fetchData(completion: @escaping () -> Void) {} correctly places@escapingbefore the closure type. Options A, C, and D have incorrect syntax.Final Answer:
func fetchData(completion: @escaping () -> Void) {} -> Option DQuick Check:
Correct syntax = func fetchData(completion: @escaping () -> Void) {} [OK]
- Placing @escaping before parameter name
- Omitting @escaping for delayed closures
- Writing 'escaping' without @ symbol
func performTask(completion: @escaping () -> Void) {
DispatchQueue.main.async {
completion()
}
print("Task started")
}
performTask {
print("Task completed")
}Solution
Step 1: Understand async dispatch behavior
The closure passed toDispatchQueue.main.asyncruns later, after the current function finishes.Step 2: Trace print statements order
"Task started" prints immediately. Then the closure runs and prints "Task completed".Final Answer:
Task started\nTask completed -> Option CQuick Check:
Async closure runs after print [OK]
- Assuming closure runs before print
- Ignoring async dispatch delay
- Confusing order of print statements
func saveData(completion: () -> Void) {
DispatchQueue.global().async {
// Save operation
completion()
}
}Solution
Step 1: Analyze closure usage inside async block
The closure is called asynchronously after the function returns, so it must be marked@escaping.Step 2: Check function parameter declaration
The parameter lacks@escaping, causing a compile error.Final Answer:
Missing @escaping before closure parameter -> Option AQuick Check:
Async closure needs @escaping [OK]
- Forgetting @escaping for async closures
- Assuming closure is synchronous by default
- Adding unnecessary optional to closure
class NetworkManager {
var completionHandler: (() -> Void)?
func requestData(completion: ???) {
self.completionHandler = completion
// Simulate network delay
DispatchQueue.global().asyncAfter(deadline: .now() + 1) {
self.completionHandler?()
}
}
}Solution
Step 1: Understand closure storage and delayed call
The closure is saved in a property and called later asynchronously, so it must be@escaping.Step 2: Evaluate options for closure parameter
Only completion: @escaping () -> Void correctly marks the closure as@escaping. Options A, B, and D are incorrect or unnecessary here.Final Answer:
completion: @escaping () -> Void -> Option BQuick Check:
Stored closures must be @escaping [OK]
- Omitting @escaping when storing closures
- Using @autoclosure unnecessarily
- Marking closure without @escaping for delayed call
Ready to prove it?
Pass the test and this pattern moves unknown
