Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct way of use strongSelf in swift?

In Objective-C in non-trivial blocks I noticed usage of weakSelf/strongSelf.

What is the correct way of usage strongSelf in Swift? Something like:

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

So for each line containing self in closure I should add strongSelf check?

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

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

Is there any way to make aforesaid more elegant?

like image 539
Голобояр Євген Avatar asked Jul 16 '15 12:07

Голобояр Євген


4 Answers

Using strongSelf is a way to check that self is not equal to nil. When you have a closure that may be called at some point in the future, it is important to pass a weak instance of self so that you do not create a retain cycle by holding references to objects that have been deinitialized.

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

Essentially you are saying if self no longer exists do not hold a reference to it and do not execute the action on it.

like image 67
Max Avatar answered Dec 22 '22 10:12

Max


Swift 4.2 🔸

guard let self = self else { return }

Ref: https://benscheirman.com/2018/09/capturing-self-with-swift-4-2/
Ref2: https://www.raywenderlich.com/5370-grand-central-dispatch-tutorial-for-swift-4-part-1-2

like image 22
Sentry.co Avatar answered Dec 22 '22 12:12

Sentry.co


Your use of strongSelf appears to be directed at only calling the doSomethingN() method if self is not nil. Instead, use optional method invocation as the preferred approach:

self?.doSomethingN()
like image 27
GoZoner Avatar answered Dec 22 '22 10:12

GoZoner


another way to use weak selfwithout using strongSelf

{[weak self] () -> void in 
      guard let `self` = self else { return }
      self.doSomething()
}
like image 44
Cruz Avatar answered Dec 22 '22 11:12

Cruz