Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use unowned when you can use weak? [duplicate]

Tags:

swift

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.

like image 471
Boon Avatar asked Dec 26 '22 07:12

Boon


1 Answers

Apple says that the rules are as follows:

  • Use a weak reference whenever it is valid for that reference to become nil at some point during its lifetime.
  • Use an unowned reference when you know that the reference will never be nil once it has been set during initialization.

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.

like image 168
Sergey Kalinichenko Avatar answered Dec 27 '22 21:12

Sergey Kalinichenko