Say you have a closure that uses self
, so you pass it to another function where it's defined as @escaping
do you still need to use weak/unowned self
?
To give an example, imagine you pass a closure:
func doAction(@escaping action: () -> Void)
And let's say that you call that function, providing for the action
parameter a closure:
{ // here self is a class/actior
self. ...
}
You still need need to use [weak self]
inside the closure, right?
That entirely depends on the lifetimes and semantics of self
and of the @escaping
closure, which aren’t given here.
- If the closure won’t outlive
self
, and capturing self
strongly does not create a circular reference, it doesn’t matter. I’d use a strong capture for convenience.
- If the closure won’t outlive
self
, but a strong capture would create a circular reference, use [unowned self]
.
- If the closure may outlive all other references to
self
, and you want the closure to keep self
alive, capture self
strongly.
- If the closure may outlive all other references to
self
, and you don’t want the closure to keep self
alive, use [weak self]
.
8 Likes