When to use unowned reference instead of weak! Top Developer’s secret that you didn’t know
Swift uses weak reference
and unowned reference
to avoid strong reference.
weak reference
can be achieved with weak self
and unowned
with unowned self
. Mostly, when you don’t know what to use, using weak self
is fine. But you are a developer. Developer always tries to understand what’s lying behind. So, I will explain the most common use cases for unowned self
.
Use unowned when it should not be nil
In the CreditCard class, customer is a constant. So it must always have a value. In this case, you can use it as unowned to avoid circular references.
Lazy initialization
When you initialize a property value after an object has been initialized and just before using it via Lazy, circular references can occur because the closure acquires the value for the variable. So when you access self
, you can use [unowned self], since self assumes that it has a value.
Conclusion
- Use weak when you don’t know what to use. (In most cases, it’s fine)
- Use unowned when you are sure that it’s not nil
- Use unowned on lazy initialization