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

Viewed 5820

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.

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.

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.

Related