Capture lists in closures in Swift - Time & Space Complexity
When using capture lists in closures, it is important to understand how the closure accesses variables and how often it runs. This helps us see how the program's work grows as input changes.
We want to know how the closure's execution time changes with the size of captured data or repeated calls.
Analyze the time complexity of the following code snippet.
func makeIncrementer(amount: Int) -> () -> Int {
var total = 0
return { [amount] in
total += amount
return total
}
}
let incrementByFive = makeIncrementer(amount: 5)
print(incrementByFive())
print(incrementByFive())
This code creates a closure that captures a constant value and updates a variable each time it runs.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The closure increments a variable and returns it each time it is called.
- How many times: Each call to the closure runs the increment operation once.
The closure runs a simple addition each time it is called, regardless of input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 calls | 10 additions |
| 100 calls | 100 additions |
| 1000 calls | 1000 additions |
Pattern observation: The work grows directly with the number of times the closure is called, one addition per call.
Time Complexity: O(n)
This means the total work grows linearly with the number of closure calls.
[X] Wrong: "The capture list makes the closure run faster or slower depending on the size of captured variables."
[OK] Correct: The capture list only controls how variables are captured, not how many times the closure runs or how much work each call does.
Understanding how closures capture variables and how that affects repeated execution helps you reason about performance in real Swift code. This skill shows you can think about both code behavior and efficiency.
What if the closure captured a large array instead of a single integer? How would the time complexity change when calling the closure multiple times?