Intro to Weak vs Unowned in Swift

As I’m sure many of us who are coding in Swift often see two keywords that are familiar to us which are weak and unowned . Today I want to discuss the distinction between the two keywords and how you should implement this in your application.

In order to discuss about weak and unowned , we need to first understand ARC(Automatic Reference Count). ARC is used to to track and manage your application’s memory usage. Whenever we create an instance of a class, ARC carves up a chunk of memory in order to store information of it’s type, properties, and values. When an instance is no longer in use, ARC frees up the memory, and allows the memory to be used for other purposes. Any instances that are deallocated will no longer have access to it’s properties or methods. Each time an instance is created or referenced, the ARC goes up by one.

In Swift, all instances are created as a strong reference by default unless we declare it as weak or unowned . By stating our instances as weak or unowned , we are giving it the ability to be deallocated. The reason why we want to be able to deallocate instances is because of strong reference cycle which can cause memory leaks.

class Restaurant {
var customer: Customer?
}
class Customer {
var restaurant: Restaurant?
}

Here we a Restaurant instance which has a Customer instance as it’s properties. If we were to create an instance of either class, and want to deallocate, we would not able to do so because of a strong reference cycle. Both instances holds a strong reference of each other causing the ARC to remain the same.

Weak

class Restaurant {
weak var customer: Customer?
}
class Customer {
var restaurant: Restaurant?
}

One of the solution for strong reference cycle is to declare your properties as weak . By having weak references, ARC automatically sets the reference to nil when it is deallocated. Take a look at the example of our restaurant and customer class, this time we set our customer property in restaurant class as a weak variable. If we want to set our customer property as nil, it will successfully deallocate and break the strong reference cycle.

Owned

class Restaurant {
unowned var ingredient: Ingredient
var customer: Customer?
}
class Ingredient {
var restaurant: Restaurant?
}

owned reference are very similar to weak reference, however owned reference must have a value. We cannot set our owned reference to nil. A tip is to use weak reference if know your value will be nil at some point in it’s life time, and use owned if you’re certain there is a value. Let’s take a look at the example above. Here we have a restaurant and ingredient class, restaurant class has a unowned ingredient. We know there must be ingredient in our restaurant, however we might or might not have a customer, therefore we have to use unowned in this case.


Thanks for tuning in! 😎

Show your support

Clapping shows how much you appreciated Henry Chan’s story.