what a different between Weak and unowned?

Generated on 9/9/2024

1 search

In Swift, both weak and unowned references are used to avoid strong reference cycles, but they have different characteristics and use cases:

  1. Weak References:

    • Optional: Weak references are always optional types. They automatically become nil when the object they reference is deinitialized.
    • Memory Overhead: Swift allocates a weak reference storage for the destination object the first time it's weakly referenced, which introduces some memory overhead.
    • Use Case: Use weak references when the referenced object can be deallocated before the reference itself, and you want to avoid a strong reference cycle without risking a crash.
  2. Unowned References:

    • Non-Optional: Unowned references directly hold their destinations and do not use extra memory. They can be non-optional and constant.
    • No Memory Overhead: They take less time to access than weak references because they don't require additional storage.
    • Use Case: Use unowned references when you can guarantee that the reference will not outlive the object it points to. If the object is deallocated before the reference, accessing it will cause a crash.

In summary, weak references are safer when the lifetime of the referenced object is uncertain, while unowned references are more efficient when you can ensure the referenced object will outlive the reference. For more details, you can refer to the session Analyze heap memory (26:57).