Memory implications of captures in Swift - Time & Space Complexity
When a Swift closure captures variables, it can affect how much memory the program uses over time.
We want to see how the memory use grows as the closure captures more data or runs more times.
Analyze the time complexity of the following code snippet.
func makeIncrementer() -> () -> Int {
var total = 0
return {
total += 1
return total
}
}
let increment = makeIncrementer()
print(increment())
print(increment())
This code creates a closure that captures a variable and updates it each time the closure runs.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The closure increments and returns the captured variable
total. - How many times: Each time the closure is called, it updates
totalonce.
Each call to the closure does a simple addition and returns a value, so the work per call stays the same.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 increments |
| 100 | 100 increments |
| 1000 | 1000 increments |
Pattern observation: The number of operations grows directly with how many times the closure runs.
Time Complexity: O(n)
This means if you call the closure n times, the total work grows in a straight line with n.
[X] Wrong: "The closure captures the variable once, so calling it many times doesn't add any cost."
[OK] Correct: Each call still does work to update and return the variable, so the total work grows with calls.
Understanding how closures capture variables and how that affects memory and work helps you write clear and efficient Swift code.
"What if the closure captured a large array and appended to it each time? How would the time complexity change?"