Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do we need to repeat `guard let self = self else { return }` inside each nested closure to keep strong self?

Tags:

swift

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.

like image 801
pvllnspk Avatar asked Mar 03 '21 08:03

pvllnspk


People also ask

Do you need weak self in your closure?

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.


2 Answers

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.

like image 139
Andreas Oetjen Avatar answered Oct 16 '22 17:10

Andreas Oetjen


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.

like image 25
πter Avatar answered Oct 16 '22 18:10

πter