0Pricing
Swift Academy · Lesson

Capture Lists and Weak Self

Avoid retain cycles with [weak self].

The Retain Cycle Risk

When an object stores an escaping closure that captures self strongly, each keeps the other alive forever — a retain cycle that leaks memory.

A Strong Cycle

The closure captures self strongly and self holds the closure — neither is ever freed:

class Owner {
    var onEvent: (() -> Void)?
    func setup() {
        onEvent = { print(self.describe()) }  // strong self -> cycle
    }
    func describe() -> String { "Owner" }
}
let o = Owner(); o.setup()
o.onEvent?()  // "Owner"  (but leaks)

All lessons in this course

  1. Capturing Values by Reference
  2. Escaping Closures
  3. Capture Lists and Weak Self
  4. Autoclosures
← Back to Swift Academy