Home > Enterprise >  What is the usage of guard let self = self else { return }
What is the usage of guard let self = self else { return }

Time:02-07

I just learned how to use the Result type recently from enter image description here

CodePudding user response:

Your concern is correct. Because getFollowers is an async task, user could go back to previous screen while the task is running. In that case, self could be nil and the return is okay.

On the other hand, to make sure there's no problem with completion block of getFollowers task, self will be captured as strong reference, that could cause memory leak even if user already leave that screen. He uses weak self to prevent that happens.

CodePudding user response:

Its because the closure defines its reference to self as being weak, this means if self is released, the block closure will not prevent self from being destructed, getting a reference count of 0. You can deal with this in the code in the closure, by using all references to self as self?, but this mean self could became nil mid way being executed, by using guard let self = self else { return }, you are saying if execution gets here, I want a strong reference to it, so the object will continue being available until the execution of the of the closure complete, basically all or nothing. This in the past could only happen with multi threaded apps, but with apples new async thread model making cooperative threads more common this is potential more possible.

  •  Tags:  
  • Related