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?"
Practice
Solution
Step 1: Understand default capture behavior
By default, Swift closures capture variables strongly, meaning they keep a reference to the original variable.Step 2: Recognize memory implications
If the closure and the captured variable reference each other, it can cause a retain cycle, leading to memory leaks.Final Answer:
The closure keeps a strong reference, potentially causing memory leaks if not handled. -> Option AQuick Check:
Strong capture = possible memory leak [OK]
- Thinking variables are copied by default
- Assuming closures do not hold references
- Believing variables auto-release on capture
self in a Swift closure?Solution
Step 1: Recall capture list syntax
Capture lists are declared inside square brackets before the closure parameters, e.g., [weak self].Step 2: Match correct syntax
{ [weak self] in print(self) } uses the correct syntax: { [weak self] in ... }.Final Answer:
{ [weak self] in print(self) } -> Option DQuick Check:
Capture list uses square brackets [weak self] [OK]
- Using parentheses instead of square brackets
- Placing 'weak' outside capture list
- Incorrect arrow syntax in capture list
class Person {
var name = "Alice"
lazy var greet: () -> Void = { [unowned self] in
print("Hello, \(self.name)!")
}
}
let p = Person()
p.greet()Solution
Step 1: Analyze closure capture
The closure captures self as unowned, meaning it expects self to always exist when called.Step 2: Check code execution
Instance p is created, greet closure is called, printing "Hello, Alice!" using self.name.Final Answer:
Hello, Alice! -> Option CQuick Check:
Unowned capture prints value safely if object exists [OK]
- Expecting Optional wrapping in output
- Thinking unowned causes runtime error immediately
- Assuming empty string prints
class ViewController {
var title = "Main"
lazy var printTitle = {
print(self.title)
}
}
let vc = ViewController()
vc.printTitle()Solution
Step 1: Identify capture type
The closure captures self strongly by default, which can cause retain cycles if ViewController holds the closure.Step 2: Fix with weak capture
Adding [weak self] in the capture list prevents retain cycle by capturing self weakly.Final Answer:
Retain cycle due to strong self capture; fix with [weak self] capture list. -> Option BQuick Check:
Strong capture in closures can cause retain cycles [OK]
- Ignoring retain cycles in lazy properties
- Assuming no capture means no memory issues
- Confusing syntax errors with memory issues
data. You want to ensure the closure does not keep data alive if the class instance is deallocated, but still access data safely inside the closure. Which capture strategy should you use?Solution
Step 1: Understand capture effects on memory
Strong capture keeps data alive, which may cause memory leaks if the class is deallocated.Step 2: Choose safe capture method
Weak capture allows data to be nil if deallocated; unwrapping safely avoids crashes.Step 3: Compare with unowned and no capture
Unowned assumes data always exists, risking crashes. Not capturing requires passing data every time, which may be inconvenient.Final Answer:
Capturedataweakly and unwrap it safely inside the closure. -> Option AQuick Check:
Weak capture + safe unwrap = safe memory handling [OK]
- Using unowned and risking runtime crashes
- Strong capture causing retain cycles
- Ignoring safe unwrapping of weak references
Ready to prove it?
Pass the test and this pattern moves unknown
