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

前端 未结 9 1933
耶瑟儿~
耶瑟儿~ 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:43

    Update 11/2016

    I wrote an article on this extending this answer (looking into SIL to understand what ARC does), check it out here.

    Original answer

    The previous answers don't really give straightforward rules on when to use one over the other and why, so let me add a few things.

    The unowned or weak discussion boils down to a question of lifetime of the variable and the closure that references it.

    Scenarios

    You can have two possible scenarios:

    1. The closure have the same lifetime of the variable, so the closure will be reachable only until the variable is reachable. The variable and the closure have the same lifetime. In this case you should declare the reference as unowned. A common example is the [unowned self] used in many example of small closures that do something in the context of their parent and that not being referenced anywhere else do not outlive their parents.

    2. The closure lifetime is independent from the one of the variable, the closure could still be referenced when the variable is not reachable anymore. In this case you should declare the reference as weak and verify it's not nil before using it (don't force unwrap). A common example of this is the [weak delegate] you can see in some examples of closure referencing a completely unrelated (lifetime-wise) delegate object.

    Actual Usage

    So, which will/should you actually use most of the times?

    Quoting Joe Groff from twitter:

    Unowned is faster and allows for immutability and nonoptionality.

    If you don't need weak, don't use it.

    You'll find more about unowned* inner workings here.

    * Usually also referred to as unowned(safe) to indicate that runtime checks (that lead to a crash for invalid references) are performed before accessing the unowned reference.

提交回复
热议问题