8

I always using [weak self] in swift closure to prevent reference cycle. Here is the code below, is it the correct way?

someTask(completion: {[weak self] (result) in
        if self == nil {  
            return
        }

        //is it safe when reach here? 

        self!.xxx = yyy
        self!.doLongTermWork()
        self!.finish()  //will crash when self is nil?
    })

Weak self does not keep a strong hold on the instance. So when self.doLongTermWork(), will self be set to nil again somewhere else?

matt
  • 515,959
  • 87
  • 875
  • 1,141
James Zhang
  • 95
  • 1
  • 4

3 Answers3

14

Your pattern has race condition. If self was deallocated at the exact same time as your completion handler closure was executing, it could crash. As a general rule, avoid using the ! forced unwrapping operator if you can.

  1. I’d lean towards the guard “early exit” pattern (reducing nested braces, making code easier to read). The standard Swift 4.2 solution is:

    someTask { [weak self] result in
        guard let self = self else { return }
    
        self.xxx = yyy
        self.doLongTermWork()
        self.finish()
    }
    
  2. Before Swift 4.2, which implemented SE-0079, we would have to do something like:

    someTask { [weak self] result in
        guard let strongSelf = self else { return }
    
        strongSelf.xxx = yyy
        strongSelf.doLongTermWork()
        strongSelf.finish()
    }
    

    You can see why we prefer the Swift 4.2 improvement, as this strongSelf syntax is inelegant.

  3. The other obvious alternative is just:

    someTask { [weak self] result in
        self?.xxx = yyy
        self?.doLongTermWork()
        self?.finish()
    }
    

    Sometimes you need the “weak self - strong self dance” (the first two alternatives), but it would not appear to be the case here. This is likely sufficient.

There are other scenarios/edge cases that one might contemplate, but these are the basic approaches.

Rob
  • 415,655
  • 72
  • 787
  • 1,044
7

You said:

someTask(completion: {[weak self] (result) in
    if self == nil {  
        return
    }
    //is it safe when reach here? 
    self!.xxx = yyy
})

No! You have not retained self, so in theory it might become nil at any time during the execution of the closure. It probably won't, but "probably" is not good enough. And exclamation marks are always an invitation to crash.

Do the weak-strong dance, and do it correctly:

someTask(completion: {[weak self] (result) in
    if let self = self {  // or let `self` before Swift 4
        // here, self is safe, because you made the reference strong again
        self.xxx = yyy
    }
})
matt
  • 515,959
  • 87
  • 875
  • 1,141
0

You can use it like this from Swift 4.2

someTask(completion: {[weak self] (result) in
    guard let self = self { return }

    //it safe when reach here always

    self.xxx = yyy
    self.doLongTermWork()
    self.finish()
})
Suhit Patil
  • 11,748
  • 3
  • 50
  • 60
Keshav
  • 2,965
  • 3
  • 25
  • 30
  • Thanks. But I have another confusion. When I want to weak many objects at a time, ex: `{[weak self], [weak obj1], [weak obj2].. in ...}`. Is it thread safe to prevent the race condition. – James Zhang Feb 16 '19 at 02:44
  • @JamesZhang - The syntax would be `someTask { [weak self, weak obj1, weak obj2] in ... }`. And yes, you can do that, but in practice it’s extremely rare that you’d need to do that. You’d have to give us a practical example of when you intended to do this. But these `weak` capture references are for avoiding strong reference cycles and race conditions: It is, by no means, any guarantee of thread-safety. That’s a different and much broader topic. – Rob Feb 16 '19 at 05:24