What is the correct way of use strongSelf in swift?
Asked Answered
D

5

11

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?

Downhaul answered 16/7, 2015 at 12:41 Comment(2)
There's nothing special about strongSelf here. It's just a variable name. Perhaps add the Objective-C code you're hoping to replicate? What you're doing here is no different from simply self?.doSomething()Accustomed
Please check this question there is [unowned self] in swift : #24320847 and dhoerl.wordpress.com/2013/04/23/…Takao
U
33

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.

Underdone answered 16/7, 2015 at 13:36 Comment(1)
You can also substitute if let with guard let here to avoid another nesting (indentation) level: guard let strongSelf = self else { return }Fuze
H
17
S
7

another way to use weak selfwithout using strongSelf

{[weak self] () -> void in 
      guard let `self` = self else { return }
      self.doSomething()
}
Satiety answered 2/12, 2016 at 13:19 Comment(1)
I love this BUT be careful. Chris Lattner has specifically stated this is a compiler bug lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160118/…Tropo
P
5

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()
Poteen answered 16/7, 2015 at 15:14 Comment(0)
S
1

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

There is also way to use as weak or unowned if you trying to avoid a retain cycles. It is achieved by passing [unowned self] or [weak self] before closure's parameters.

Succinct answered 16/7, 2015 at 13:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.