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?