Captures strongweak references and retain cycles

suggest change
class MyClass {
    func sayHi() { print("Hello") }
    deinit { print("Goodbye") }
}

When a closure captures a reference type (a class instance), it holds a strong reference by default:

let closure: () -> Void
do {
    let obj = MyClass()
    // Captures a strong reference to `obj`: the object will be kept alive
    // as long as the closure itself is alive.
    closure = { obj.sayHi() }
    closure()  // The object is still alive; prints "Hello"
} // obj goes out of scope
closure()  // The object is still alive; prints "Hello"

The closure’s capture list can be used to specify a weak or unowned reference:

weak
assumedunownedcrash!

For more information, see the Memory Management topic, and the Automatic Reference Counting section of The Swift Programming Language.

Retain cycles

If an object holds onto a closure, which also holds a strong reference to the object, this is a retain cycle. Unless the cycle is broken, the memory storing the object and closure will be leaked (never reclaimed).

BAD:SOLUTION:[weak self] inguard let strongSelf = self else { return }

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents