Escaping closures (@escaping) in Swift - Time & Space Complexity
When using escaping closures in Swift, it's important to understand how the program's work grows as input changes.
We want to see how the time to run the code changes when the number of tasks inside the closure changes.
Analyze the time complexity of the following code snippet.
func performTasks(tasks: [@escaping () -> Void], completion: @escaping () -> Void) {
for task in tasks {
DispatchQueue.global().async {
task()
}
}
DispatchQueue.main.async {
completion()
}
}
This code runs a list of tasks asynchronously and then calls a completion closure after scheduling all tasks.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the array of tasks to schedule each one.
- How many times: Once for each task in the input array.
As the number of tasks grows, the number of times the loop runs grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 task schedules |
| 100 | 100 task schedules |
| 1000 | 1000 task schedules |
Pattern observation: The work grows directly with the number of tasks.
Time Complexity: O(n)
This means the time to schedule tasks grows in a straight line as the number of tasks increases.
[X] Wrong: "Because tasks run asynchronously, the time complexity is constant no matter how many tasks there are."
[OK] Correct: Scheduling each task still takes time, so the total scheduling work grows with the number of tasks, even if the tasks run in parallel later.
Understanding how escaping closures and asynchronous calls affect time helps you explain how your code scales and performs in real apps.
"What if the completion closure was called only after all tasks finished? How would that affect the time complexity?"
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
