Shall we always use [unowned self] inside closure in Swift

前端 未结 9 1903
耶瑟儿~
耶瑟儿~ 2020-11-22 05:22

In WWDC 2014 session 403 Intermediate Swift and transcript, there was the following slide

\"enter

9条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 05:42

    According to Apple-doc

    • Weak references are always of an optional type, and automatically become nil when the instance they reference is deallocated.

    • If the captured reference will never become nil, it should always be captured as an unowned reference, rather than a weak reference

    Example -

        // if my response can nil use  [weak self]
          resource.request().onComplete { [weak self] response in
          guard let strongSelf = self else {
            return
          }
          let model = strongSelf.updateModel(response)
          strongSelf.updateUI(model)
         }
    
        // Only use [unowned self] unowned if guarantees that response never nil  
          resource.request().onComplete { [unowned self] response in
          let model = self.updateModel(response)
          self.updateUI(model)
         }
    

提交回复
热议问题