0Pricing
Swift Academy · Lesson

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

  1. Closures & Capture basics
  2. Capture lists — weak/unowned & value capture
  3. Escaping vs non-escaping, autoclosures
← Back to Swift Academy