Jovan Jovanovski Jovan Jovanovski - 11 months ago 48
Swift Question

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

Answer Source

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