In Swift, there is option to use unowned
or weak
. Why use unowned
when you can use weak
? It seems the two are almost the same, with weak
being safer.
Apple says that the rules are as follows:
weak
reference whenever it is valid for that reference to become nil
at some point during its lifetime.The reason for having unowned
in the first place is that weak
must be of an optional type, while unowned
will be non-optional. This lets you avoid unwrapping and/or checking, which is associated with variables of optional type.
Both kinds of references carry the same costs: Swift keeps track of them, so that it could set weak
references to nil
, and mark unowned
references invalid when the object they reference is destroyed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With