what is the difference between weak and unowned?

Asked on 09/06/2024

1 search

In Swift, weak and unowned references are used to avoid strong reference cycles, which can prevent objects from being deallocated. Here's a summary of their differences and when to use them:

  • Weak References:

    • Weak references are always optional types. They become nil after their destination objects are deinitialized.
    • They are useful when you don't know how long the destination will live, as they allow the destination to be deallocated when no strong references exist.
    • Weak references come with some overhead because Swift allocates a weak reference storage for the destination object the first time it's weakly referenced.
    • They are a good default choice when you need to avoid strong reference cycles.
  • Unowned References:

    • Unowned references directly hold their destination objects, meaning they don't use extra memory and are faster to access than weak references.
    • They can be non-optional and constant, but they must always point to a valid object. If the object is deinitialized, accessing an unowned reference will cause a crash.
    • Use unowned references when you can guarantee that the reference will not outlive its destination, saving memory and time.

For more detailed information, you can refer to the session Analyze heap memory (26:51) from WWDC 2024, which discusses the performance comparison between weak and unowned references.