I understand the usage and superficial differences between weak
and unowned
in Swift:
The simplest examples I\'ve seen is that if there is
A weak
reference is actually set to nil and you must check it when the referent deallocates and an unowned
one is set to nil, but you are not forced to check it.
You can check a weak
against nil with if let
, guard
, ?
, etc, but it makes no sense to check an unowned
, because you think that is impossible. If you are wrong, you crash.
I have found that in-practice, I never use unowned. There is a minuscule performance penalty, but the extra safety from using weak is worth it to me.
I would leave unowned usage to very specific code that needs to be optimized, not general app code.
The "why does it exist" that you are looking for is that Swift is meant to be able to write system code (like OS kernels) and if they didn't have the most basic primitives with no extra behavior, they could not do that.
NOTE: I had previously said in this answer that unowned is not set to nil. That is wrong, a bare unowned
is set to nil. A unowned(unsafe)
is not set to nil and could be a dangling pointer. This is for high-performance needs and should generally not be in application code.