10

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?

  • 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()` – nhgrif Jul 16 '15 at 12:47
  • Please check this question there is `[unowned self]` in swift : http://stackoverflow.com/questions/24320347/shall-we-always-use-unowned-self-inside-closure-in-swift and https://dhoerl.wordpress.com/2013/04/23/i-finally-figured-out-weakself-and-strongself/ – Ashish Kakkad Jul 16 '15 at 12:51

5 Answers5

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.

Max
  • 1,143
  • 7
  • 7
  • 1
    You can also substitute `if let` with `guard let` here to avoid another nesting (indentation) level: `guard let strongSelf = self else { return }` – Jonathan Cabrera Aug 09 '18 at 18:16
16

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

Sentry.co
  • 5,355
  • 43
  • 38
7

another way to use weak selfwithout using strongSelf

{[weak self] () -> void in 
      guard let `self` = self else { return }
      self.doSomething()
}
Cruz
  • 2,602
  • 19
  • 29
  • 8
    I love this BUT be careful. Chris Lattner has specifically stated this is a compiler bug https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160118/007425.html – wuf810 Jan 31 '17 at 19:21
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()
GoZoner
  • 67,920
  • 20
  • 95
  • 145
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.

s1ddok
  • 4,615
  • 1
  • 18
  • 31