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

2.7k Views Asked by At

I just learned how to use the Result type recently from Sean Allen's video, and I get the idea of using it. However, while I was writing a code, there is a line I don't understand.

The line is 87 in the picture (or this -> guard let self = self else { return } ) At first, I was just doing the same stuff as he did, but I wonder why he add the line in the code. I think he wrote it because the self can be nil and wanted to make sure if the self is not nil and return from the function if it gets nil.

And my question is

  1. when or in which situation the self can be nil? and
  2. if self gets nil, I think it won't trigger the following line (the one for checking the result), so both of the updateUI function and presentGFAlert... function won't be triggered and nothing shows up on the screen, right?

enter image description here

2

There are 2 best solutions below

2
Quang Hà On BEST ANSWER

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.

1
Nathan Day On

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.