When to Use Unowned vs Weak?

When to Use Unowned vs Weak?

The main difference between weak and unowned is that weak is optional while unowned is non-optional. By declaring it weak you get to handle the case that it might be nil inside the closure at some point. If you try to access an unowned variable that happens to be nil, it will crash the whole program.

When should you use unowned or weak?

Use a weak reference whenever it is valid for that reference to become nil at some point during its lifetime. Conversely, use an unowned reference when you know that the reference will never be nil once it has been set during initialization.

What is difference between weak and unowned?

The first difference you need to know about is that an unowned reference is always expected to have a value. ... When that happens, the reference is set to nil . Because a weak reference can be set to nil , it is always declared as an optional. That is the second difference between weak and unowned references.

Alexander Ross
Author

Alexander Ross

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.