What is the correct way to use strongSelf in fast?

In Objective-C, in non-trivial blocks, I noticed the use of weakSelf / strongSelf.

What is the correct way to use strongSelf in Swift? Sort of:

if let strongSelf = self { strongSelf.doSomething() } 

So, for every line containing self in close, should I add a strongSelf check?

 if let strongSelf = self { strongSelf.doSomething1() } if let strongSelf = self { strongSelf.doSomething2() } 

Is there a way to make the above more elegant?

+9
source share
5 answers

Using strongSelf is a way to verify that self not nil. When you have a closure that may be triggered at some point in the future, it is important to pass an instance of weak self so that you do not create a save loop while maintaining references to objects that have been de-initialized.

 {[weak self] () -> void in if let strongSelf = self { strongSelf.doSomething1() } } 

Essentially, you say that if I no longer exist, do not keep a link to it and do not perform an action on it.

+25
source

another way to use weak self without using strongSelf

 {[weak self] () -> void in guard let `self` = self else { return } self.doSomething() } 
+6
source

Your use of strongSelf seems directional only when you call the doSomethingN() method, if self not equal to zero. Use the preferred method instead:

 self?.doSomethingN() 
+3
source

If you use self in your closure, it is automatically used as strong.

There is also a way to use as weak or unowned if you are trying to avoid save cycles. This is achieved by skipping [unoccupied self] or [weak self] before closing parameters.

+1
source

All Articles