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?
Practice
Solution
Step 1: Understand what capture lists do
Capture lists let you specify how variables are captured inside closures, either by strong, weak, or unowned references.Step 2: Identify the main purpose
The main purpose is to control how variables are stored and referenced to avoid memory leaks or unexpected behavior.Final Answer:
To control how variables are stored and referenced inside the closure -> Option AQuick Check:
Capture list purpose = control variable capture [OK]
- Confusing capture lists with closure parameters
- Thinking capture lists define return types
- Assuming capture lists affect closure execution timing
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
let closure = { [weak self] in print(self) } uses the correct syntax: [weak self] inside square brackets before the closure body.Final Answer:
let closure = { [weak self] in print(self) } -> Option CQuick Check:
Capture list syntax = [weak self] [OK]
- Omitting square brackets around capture list
- Placing 'weak' outside the brackets
- Using parentheses instead of brackets
class Example {
var value = 10
lazy var closure: () -> Void = { [unowned self] in
print(self.value)
}
}
let example = Example()
example.value = 20
example.closure()Solution
Step 1: Understand unowned self capture
The closure captures self as unowned, meaning it references the original object without increasing retain count.Step 2: Check value at closure call
example.value is updated to 20 before calling closure, so print(self.value) outputs 20.Final Answer:
20 -> Option AQuick Check:
Unowned self captures current value = 20 [OK]
- Thinking closure captures old value copy
- Confusing unowned with weak causing nil
- Expecting runtime error without object deallocation
class Test {
var count = 0
lazy var closure: () -> Void = { [weak self] in
self.count += 1
print(self.count)
}
}Solution
Step 1: Analyze weak self usage
When capturing self as weak, self becomes an optional inside the closure.Step 2: Check code for optional unwrapping
The code uses self.count directly without unwrapping, causing a compile error.Final Answer:
Cannot use weak self without unwrapping optional -> Option DQuick Check:
Weak self requires optional unwrapping [OK]
- Using weak self as non-optional
- Ignoring optional chaining or guard let
- Assuming lazy closures can't have capture lists
Solution
Step 1: Understand capture by copy
To capture a variable by making a copy, you assign it inside the capture list using syntax like [value = variable].Step 2: Evaluate options
[value = variable] uses the correct syntax to copy the variable's value into the closure's capture list.Final Answer:
[value = variable] -> Option BQuick Check:
Copy capture syntax = [value = variable] [OK]
- Using weak or unowned which capture references
- Assuming [copy variable] is valid syntax
- Not assigning variable inside capture list
Ready to prove it?
Pass the test and this pattern moves unknown
