In a situation where self
could conceivably be nil
at the time it's used in the closure, you're compelled to use weak
semantics (or risk a crash).
In a case where you can reason that self
will never be nil
, you can choose to specify either: "choose" in the sense that both are correct and will work. Arguably one could be considered "more correct" than the other, in the sense that both semantics satisfy the requirements but one is more specific.
Two reasons you might want to specified unowned
instead of self
:
- Convenience
- Documentation
An unowned
reference will be more convenient to use because it doesn't need to be unwrapped. It may also be more efficient, since the compiler may not have to produce as much cleanup code for safe deallocation.
In terms of documentation, you're making a kind of assertion about something your program believes to be true. If that assumption (assuming it was valid) is violated, you may like to find out about it in the form of a crash.
Subsequently, this may also make usage of the variable less exhausting: you think about it and document your reasoning that it must always exist up front, and then each time you use it, you don't have to expend further mental energy wondering "what do I do if this isn't here?".
Arguably, using a let
binding or guard
statement also achieves the latter.