Swift self: Weak or Unowned?

Not talking about the state of your relationship with your children, but the Swift concepts

Image for post
Image for post

Weak and unowned are common ways to avoid a reference cycle within your App.

Difficulty: Easy | Normal | Challenging

Prerequisites:

  • Know what optionals are

Terminology

Weak reference: A pointer to an object that doesn’t protect the pointer from being deallocated

Strong reference: A pointer to an object that protects the referred object from being deallocated by ARC

Unowned reference: A pointer to an object that protects the referred object from being deallocated by ARC, without incrementing the retain count of the object

Explanations

Strong references (the default)

This means that the reference count is increased by one.

Weak references

When you access a weak reference, it is either a valid object or nil (that is, it is an optional).

Unowned references

  1. is not an optional so will never become nil

Can lead to a dangling pointer as it will never become nil during it’s lifetime. If the object being referred is deallocated, then the App will crash when the unowned reference is used.

So…

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store