It is unacceptable, logically equivalent to the weak! to Swift

Will these blocks always fail under the same circumstances (when the closure is done, but it is freed itself)?

{ [unowned self] in //use self self.number = self.number + 1 } { [weak self] in //use self! self!.number = self!.number + 1 } 
+6
source share
3 answers

A lost link does not support a strong reference to itself, but makes the assumption that the object always has some value (it is not a nil), and if some of them are freed when the block is executed, the above code will work.

In the case of the weak, as in your example, the weak is an optional type inside the block, so there can also be a value, or it can be nil. You are responsible for checking if the value exists and call methods are called. As above, if you use the expand operator (!), When self has been freed, it will certainly work. Thus, both versions of the code fail if this happens so that the block is still executing, and self is freed up on average.

So, I suggest using weak to protect such failures, using additional checks,

 { [weak self] in if let me = self { me.number = me.number + 1 } } 
+4
source

Yes, they are equivalent. This point is unowned - it's just like weak , except that you don't have to deal with the optional and expand it, because its type is an expandable optional type; it is weak , which is always forcibly unpacked every time it appears.

+1
source

Use it like that

 { [weak self] in guard let weakSelf = self else { return } weakSelf.number = weakSelf.number + 1 } 

Thanks to the comment by @ José , remember that even if the following code is currently running, but it is considered a compiler error and should be avoided https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160118 /007425.html .

You can also unpack self as follows:

 { [weak self] in guard let `self` = self else { return } // Now you can use `self` safely self.number = self.number + 1 } 
+1
source

Source: https://habr.com/ru/post/975348/


All Articles