7

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.

pvllnspk
  • 5,471
  • 11
  • 56
  • 94

2 Answers2

6

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.

Andreas Oetjen
  • 9,151
  • 1
  • 21
  • 31
  • 1
    Yes, also including the nested blocks. In that case i personally would prefer `strongSelf`, because it's more exhaustive. – Andreas Oetjen Mar 03 '21 at 08:56
  • Yes, there is a difference, regarding retain cycles. But technically this will depend on how and how log the closure is being stored. – Andreas Oetjen Mar 03 '21 at 09:09
1

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.

πter
  • 1,549
  • 2
  • 7
  • 21