Recall & Review
beginner
What is a retain cycle in Swift closures?
A retain cycle happens when two objects hold strong references to each other, preventing them from being deallocated. In closures, this often occurs when a closure captures self strongly, and self holds the closure, causing a loop.
Click to reveal answer
beginner
How can you prevent retain cycles caused by closures in Swift?
Use a capture list with [weak self] or [unowned self] inside the closure to capture self weakly or unowned, breaking the strong reference cycle.
Click to reveal answer
intermediate
Explain the difference between [weak self] and [unowned self] in closure capture lists.
[weak self] creates an optional reference that can become nil if self is deallocated, so you must unwrap it safely. [unowned self] assumes self will never be nil during closure execution and is non-optional, but can cause a crash if self is deallocated.
Click to reveal answer
beginner
What happens if you don’t use [weak self] or [unowned self] in a closure that captures self?
The closure holds a strong reference to self, and if self also holds the closure, they keep each other alive. This causes a memory leak because neither can be freed.
Click to reveal answer
intermediate
Show a simple Swift example of a retain cycle caused by a closure capturing self strongly.
class MyClass {
var closure: (() -> Void)?
func setup() {
closure = {
print(self)
}
}
}
Here, self holds closure, and closure captures self strongly, causing a retain cycle.Click to reveal answer
What keyword can you use in a closure capture list to avoid a retain cycle by capturing self weakly?
✗ Incorrect
[weak self] captures self weakly, preventing strong reference cycles.
What is the risk of using [unowned self] in a closure?
✗ Incorrect
[unowned self] assumes self is alive; if not, accessing it causes a crash.
Why do retain cycles cause memory leaks in Swift?
✗ Incorrect
Strong references between objects prevent ARC from freeing memory.
Which of these is NOT a way to break a retain cycle in closures?
✗ Incorrect
Making self global does not prevent retain cycles; it can worsen memory issues.
In the example: closure = { print(self) }, what causes the retain cycle?
✗ Incorrect
Self and closure hold strong references to each other, causing a cycle.
Explain what a retain cycle is and how closures can cause them in Swift.
Think about how two things holding strong references to each other can never be freed.
You got /4 concepts.
Describe how to use capture lists to prevent retain cycles in Swift closures and the difference between weak and unowned captures.
Focus on how to tell the closure to hold a weaker reference to self.
You got /5 concepts.