Recall & Review
beginner
What is a capture list in Swift closures?
A capture list is a way to define how variables are captured inside a closure. It lets you specify whether to capture variables strongly, weakly, or unowned to control memory management and avoid retain cycles.
Click to reveal answer
beginner
Why do we use capture lists in closures?
We use capture lists to avoid strong reference cycles (retain cycles) by controlling how variables are captured. For example, capturing a variable as weak or unowned prevents the closure from keeping the variable alive forever.
Click to reveal answer
beginner
How do you write a capture list in a Swift closure?
You write a capture list inside square brackets before the closure parameters. For example: {[weak self] in ...} captures self weakly inside the closure.
Click to reveal answer
intermediate
What is the difference between capturing a variable as weak and unowned in a capture list?
Capturing as weak means the variable can become nil and is optional inside the closure. Capturing as unowned means the variable is expected to always exist and is non-optional, but if it doesn't exist, the program will crash.
Click to reveal answer
intermediate
Show an example of a capture list preventing a retain cycle with self in a closure.
Example:
class MyClass {
var closure: (() -> Void)?
func setup() {
closure = { [weak self] in
print(self)
}
}
}
Here, self is captured weakly to avoid a retain cycle between the class and the closure.Click to reveal answer
What does the capture list [weak self] do inside a Swift closure?
✗ Incorrect
The capture list [weak self] captures self weakly inside the closure to avoid strong reference cycles.
Where do you place the capture list in a Swift closure?
✗ Incorrect
Capture lists are placed inside square brackets before the closure parameters.
What happens if you capture a variable as unowned but it becomes nil?
✗ Incorrect
Capturing as unowned assumes the variable always exists; if it becomes nil, the program crashes.
Why might you want to use a capture list in a closure?
✗ Incorrect
Capture lists help control variable capture to avoid retain cycles and memory leaks.
Which of these is a correct capture list syntax?
✗ Incorrect
The correct syntax uses square brackets: { [weak self] in ... }
Explain what a capture list is and why it is important in Swift closures.
Think about how closures keep references to variables and how that can cause problems.
You got /4 concepts.
Describe the difference between capturing a variable as weak versus unowned in a closure's capture list.
Consider safety and lifetime guarantees of the captured variable.
You got /4 concepts.