Closures are reference types in Swift - Time & Space Complexity
When working with closures in Swift, it's important to understand how their reference nature affects performance.
We want to see how the cost of using closures grows as we create or call more of them.
Analyze the time complexity of the following code snippet.
func makeIncrementer(amount: Int) -> () -> Int {
var total = 0
let incrementer: () -> Int = {
total += amount
return total
}
return incrementer
}
let incrementByTen = makeIncrementer(amount: 10)
for _ in 1...n {
_ = incrementByTen()
}
This code creates a closure that adds a fixed amount each time it is called, then calls it n times.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Calling the closure inside the loop.
- How many times: The closure is called n times, once per loop iteration.
Each time we call the closure, it performs a simple addition and returns a value.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions and returns |
| 100 | 100 additions and returns |
| 1000 | 1000 additions and returns |
Pattern observation: The number of operations grows directly with n, the number of times the closure is called.
Time Complexity: O(n)
This means the time to run grows in a straight line as we call the closure more times.
[X] Wrong: "Closures are simple values, so calling them many times is always constant time."
[OK] Correct: Each closure call runs code, so calling it n times means n operations, not just one.
Understanding how closures behave as reference types helps you reason about performance and memory in real apps.
What if we created a new closure inside the loop each time instead of calling the same one? How would the time complexity change?