Capture lists — weak/unowned & value capture
Use capture lists to control how closures capture references and values: [weak self], unowned, and value snapshots to avoid retain cycles and subtle bugs.
Why capture lists?
Goal: Control what and how a closure captures. Use [weak self] or unowned to avoid retain cycles, and capture value snapshots when needed.
Strong capture = cycle risk
Escaping/stored closures retain captured values. Capturing self strongly here may create a retain cycle.
class Owner {
var name = "Owner"
var onDone: (() -> Void)?
func start() {
// Strong capture of self can cause a cycle if onDone is stored:
onDone = {
print("Done by", self.name) // self captured strongly
}
}
}
var o: Owner? = Owner()
o?.start()
// If nothing nils onDone or o, both can keep each other alive.All lessons in this course
- Closures & Capture basics
- Capture lists — weak/unowned & value capture
- Escaping vs non-escaping, autoclosures