unowned vs weak in Swift
2 min readDec 26, 2023
When writing code in Swift, it’s crucial to consider how we manage references to our classes so that Automatic Reference Counting (ARC) can free up memory when it’s no longer needed.
To indicate that we want to handle a reference explicitly, we can use unowned
and weak
.
The lifetime of the object is the main characteristic to determine when to use weak
or unowned
:
- If you can’t determine which of the objects involved in the relationship will have a longer lifetime, you should use
weak
. - If we can guarantee that both objects will have the same lifetime, you can use
unowned
.
Advantages of Using weak
- Since it’s optional, you will have compile-time support. In other words, the compiler will inform you that you should treat the object in question as optional.
- You will avoid crashes related to accessing an object that is no longer in memory.
Disadvantages of Using weak
- You have to introduce validations related to working with optionals.
Advantages of Using unowned
- You don’t have to use optionals.
- Accessing a property or calling a method on an
unowned
reference is slightly faster. However, the performance difference is minimal. - It communicates relationships between objects, for example, parent-child relationships. If we use
unowned
, when reading the code, we can be sure that one object cannot exist without the other.
Disadvantages of Using unowned
- Accessing an invalid
unowned
reference will cause a crash. - If the code changes, and for some reason, the relationship between objects is no longer direct, you will have to change
unowned
toweak
.
If you want to read the Spanish version of this article, you can find it here: https://asynclearn.com/blog/diferencias-entre-unowned-y-weak/