4

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
Boon
  • 40,656
  • 60
  • 209
  • 315
  • I believe the only difference is weak must be optional, whereas unowned does not, giving you a cleaner syntax when the safety you get from weak is irrelevant, and the pointer getting cleaned up is a bug. – Kevin DiTraglia Jun 26 '14 at 21:15
  • 2
    I am voting to reopen this question. I do not think this should have been closed as a duplicate. The other question asks *what* these references are, while this question asks *why* one would use one of them, when the other provides additional safety. – Sergey Kalinichenko Jun 27 '14 at 11:09

1 Answers1

10

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • "something that does not need to be done when the reference is marked unowned" Not true. The same thing has to be done with `unowned` references. Otherwise how can they guarantee that it will cause a runtime error when you access an `unowned` reference to a deallocated object? – user102008 Aug 20 '14 at 00:30
  • @user102008 You are right, they have to keep track of both kinds of references. I edited the answer, thank you! – Sergey Kalinichenko Aug 20 '14 at 01:53