I need to keep strong self inside my inner clousures.
I know that it's enough to declare [weak self]
only once for outer closure.
But what about guard let self = self else { return }
, is it enough to declare it once for outer closure also? Do we have any edge cases here ?
apiManager.doSomething(user: user) { [weak self] result in
guard let self = self else { return }
self.storageManager.doSomething(user: user) { result in
// guard let self = self else { return } <- DO WE NEED IT HERE ?
self.doSomething()
}
}
Seems like language analyser says NO - one declaration is enough , but want to be sure.
Using [weak self] is only required within situations in which capturing self strongly would end up causing a retain cycle, for example when self is being captured within a closure that's also ultimately retained by that same object.
Yes, one is enough. If you write
guard let self = self else { return }
you'll create a new local variable that will hold a strong reference to the outside weak self.
It's the same as writing
guard let strongSelf = self else { return }
and then use strongSelf
for the rest of the block.
No, in short you do not need that. If you outer closure uses [weak self]
then you should not worry about the inner closure as it will already have a weak reference to self. On the other hand if your outer closure is not using [weak self]
it is reasonable to put it for the inside block. A more detailed explation can be found here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With