Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is unowned logically equivalent to weak! in Swift

Will these blocks always fail under the same circumstances (when the closure is being executed but self was deallocated)?

{ [unowned self] in
    //use self
    self.number = self.number + 1
}

{ [weak self] in
    //use self!
    self!.number = self!.number + 1
}
like image 281
Jovan Jovanovski Avatar asked Sep 16 '14 10:09

Jovan Jovanovski


1 Answers

Unowned reference does not keep strong reference to the self, but it makes an assumption that the object always has some value (is not nil) and if, some how self deallocates while executing the block, the above code crashes.

For the case of weak, as in your example, weak is an optional type inside the block, so there could also be a value or it could be nil. It is your responsibility to check if the value exists and call methods on it. As above if you use unwrapping operator (!), when self has been deallocated, then it surely crashes. So, both the version of the code crashes, if it happens such that the block is still executing and self is deallocated in the mean time.

So, I suggest to use weak to safeguard such crashes using the optional checks,

{ [weak self] in
    if let me = self {
       me.number = me.number + 1
    }
}
like image 63
Sandeep Avatar answered Sep 27 '22 21:09

Sandeep