Captures, strong and weak references, and retain cycles
suggest changeclass 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 specify a weak or unowned reference:
let weakClosure: () -> Void
do {
let obj = MyClass()
// `weak` does not keep `obj` alive. Inside the closure it is optional.
weakClosure = { [weak obj] in obj?.sayHi() }
weakClosure() // prints "Hello"
} // obj is released; deinit prints "Goodbye"
weakClosure() // obj is nil, so this prints nothing
let unownedClosure: () -> Void
do {
let obj = MyClass()
// `unowned` does not keep `obj` alive and is not optional.
// Calling it after `obj` is deallocated traps.
unownedClosure = { [unowned obj] in obj.sayHi() }
unownedClosure() // prints "Hello"
}
// unownedClosure() here would crash
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 a closure, and that closure holds a strong reference to the object, this is a retain cycle. Unless the cycle is broken, the memory for the object and the closure is never reclaimed.
class Owner {
let thing = MyClass()
// The closure retains Owner, and Owner retains the closure.
lazy var closure: () -> Void = {
self.thing.sayHi()
}
}
Capture self weakly, then bind a strong reference for the duration of the call:
class Owner {
let thing = MyClass()
lazy var closure: () -> Void = { [weak self] in
guard let strongSelf = self else { return }
strongSelf.thing.sayHi()
}
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents