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 Dog
and a Bone
, the Bone
may have a weak reference to the Dog
(and vice versa) because the each can exist independent of each other.
On the other hand, in the case of a Human
and a Heart
, the Heart
may have an unowned
reference to the human, because as soon as the Human
becomes... "dereferenced", the Heart
can no longer reasonably be accessed. That and the classic example with the Customer
and the CreditCard
.
So this is not a duplicate of questions asking about that.
My question is, what is the point in having two such similar concepts? What are the internal differences that necessitate having two keywords for what seem essentially 99% the same thing? The question is WHY the differences exist, not what the differences are.
Given that we can just set up a variable like this: weak var customer: Customer!
, the advantage of unowned
variables being non-optional is a moot point.
The only practical advantage I can see of using
unowned
vs implicitly unwrapping aweak
variable via!
is that we can makeunowned
references constant vialet
.
... and that maybe the compiler can make more effective optimizations for that reason.
Is that true, or is there something else happening behind the scenes that provides a compelling argument to keeping both keywords (even though the slight distinction is – based on Stack Overflow traffic – evidently confusing to new and experienced developers alike).
I'd be most interested to hear from people who have worked on the Swift compiler (or other compilers).