strong, weak, unowned - Reference Counting in Swift

This article explains Apple’s memory management in Swift. Even if it gets handled mostly automatic there are still some pitfalls. Choosing the correct reference type to describe the relationship between objects help you to avoid memory leaks.

Automatic Reference Counting

Apple’s implementation for automatic tracking and managing of memory usage is called ARC (Automatic Reference Counting). It automatically frees up the memory when objects aren’t referenced anymore. To know which objects are still in use it tracks the relationship between objects by increasing and decreasing a reference count. Objects can only be deallocated when the reference count is zero. ARC only applies to instances of Classes. Structs, Enums and Value-Types are not passed by reference. This is a another great reason to use Structs instead of Classes whenever possible.

Strong

You’ll find strong references almost everywhere in Swift because it’s the default declaration of a property. This doesn’t lead to a problem when you have a linear reference flow. When you deallocate the parent and decrease the retain count, all child get decreased as well. Here is an example of a strong reference:

Weak

Unlike strong references weak don’t increase the retain count by one. So they don’t protect the object from being deallocated by the ARC. On deallocation the weak reference will be automatically set to nil. This is the reason why all weak references are mutating optional variables. Defining a constant as weak is not possible.

Unowned

Unowned references behave similar to weak ones. They don’t increase the retain count by one as well. Unlike weak references unowned don’t have to be an Optional because they aren’t automatically set to nil on deallocation. It’s important that you only use unowned references when you really know that the object will never be nil once it has been set.

weak vs. unowned - an advice from Apple

fin

Apple’s automatic memory management doesn’t prevent you from producing memory leaks. Non-linear strong references and reference cycles can prevent the retain count from reaching zero. The use of weak and unowned references help you to avoid this and keep your app memory in balance.

Written by

I’m a Software Engineer from Düsseldorf. Passionate about programming languages & technologies with vocation for agile topics.

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