Why specify [unowned self] in blocks where you depend on self being there?

后端 未结 5 1587
后悔当初
后悔当初 2021-01-19 01:37

I want self to be non-nil and I\'m sure it will be, during the blocks execution. So why explicitly specify [unowned self] ?

object.executeBlock {
    date =         


        
5条回答
  •  一个人的身影
    2021-01-19 02:36

    "The Language Guide claims you should use unowned if the closure and containing object reference each other and will be destroyed at the same time. Presumably that's to avoid the cost of safely nil'ing out a weak reference in an object that's about to dealloc anyway."

    http://www.russbishop.net/swift-capture-lists

    So [unowned self] makes self an an implicitly unwrapped optional, for the convenience of not unwrapping it yourself, at the risk of a crash if of course it is actually nil.

提交回复
热议问题