Search code examples
iosswiftclosuresweak-references

What is the meaning of following swift code?


Can anyone tell me why we use guard let self = self ??

I have seen this code while reading about GCD, I couldn't figure out what that particular line does.

DispatchQueue.global(qos: .userInitiated).async { [weak self] in
    guard let self = self else {
        return
    }

    // ...
}

Solution

  • First you are creating a block that will be executed asynchronously

    DispatchQueue.global(qos: .userInitiated).async
    

    Then inside the block the code checks if self, the object that is calling this function, is still allocated

    guard let self = self else {
      return
    }
    

    We need to check this because self is declared as weak inside the block to avoid a retain cycle (Swift closures causing strong retain cycle with self) and can be deallocated before the block is executed. That line of code checks if self is != nil, and assign it to self, otherwise it returns.