Difference between weak and unowned references explained in Swift

Swift iOS Development

12 July 2020 . 3 min read       @gurjitpt


It's a good practice to know how memory management works in Swift. Swift uses Automatic Reference Counting (ARC) to manage app's memory automatically without write any additional code. It deallocate memory of instance when it is no longer used. But sometimes we have to provide more information to avoid memory leaks and deadlocks.


ARC only applies on instance of classes because classes are reference type. It didn't applies on structures and enumerations because they are value type.


By default, class instance creates a strong reference with their methods, constants, variables etc. means it will not be deallocated until strong reference remains. Sometimes it cause memory leaks and deadlocks, we can avoid this by declaring weak reference or unowned reference.


Difference between weak reference and unowned reference

The weak reference is a optional type, means weak reference will set to nil once instance it refer to frees from memory.


On the other hand, unowned reference is a non-optional type, it never will be set to nil and always have some value.


Weak References

You can declare weak reference with weak keyword before variable or property. The following example will explain you how to use weak references.


Let's implement class Animal with property name type of String and zoo which is optional type.

class Animal {
    let name: String
    var zoo: Zoo?
    init(name: String) {
        self.name = name
    }
    deinit { 
       print("\(name) is deinitialized.")
    }
}


Now, define another class Zoo with a property location type of String and animal as a weak reference which is a optional type.

class Zoo {
     let location: String
     weak var animal: Animal?
    
     init(location: String) {
         self.location = location
     }
     deinit { 
         print("Zoo at \(location) is deinitialized.")
     }
}


Define two variables tiger and logoaZoo of optional type and set to instance. Then, link both instances together with use of unwrap.

var tiger: Animal? = Animal(name: "Amber")
var lagoaZoo: Zoo? = Zoo(location: "11th St, Corona, NY 11368, United States")
tiger!.zoo = lagoaZoo
lagoaZoo!.animal = tiger


When we set tiger variable to nil it breaks the strong reference to Animal instance and it deallocated from the memory.


As there is no more strong reference to the Animal instance so animal property will also be set to nil.

tiger = nil


If we set logoaZoo to nil it breaks strong reference to Zoo instance and will also deallocated from the memory.

lagoaZoo = nil


Unowned References

You can declare unowned reference with unowned keyword before variable or property. The following example will explain you how to use unowned references.


Define class Employee with property name of type String and bank which is optional type.

class Employee {
     let name: String
     var bank: Bank?
     init(name: String) {
         self.name = name
     }
     deinit { 
         print("\(name) is deinitialized.")
     }
}


Let's define another class Bank with property name of type String and employee which is unowned property (non-optional).

class Bank {
    let name: String
    unowned let employee: Employee
    init(name: String,employee: Employee) {
        self.name = name
        self.employee = employee
    }
    deinit { 
        print("\(name) is deinitialized.")
    }
}


Define variables ana of optional type and set to instance. Then, assign Bank instance to Employee's bank property.

var ana: Employee? = Employee(name: "Ana")
ana!.bank = Bank(name: "SPI Bank", employee: ana!)


When we set ana to nil, there is no strong reference with Employee instance and it will be deallocated.


Because there is no strong reference with Bank instance it will also be deallocated from memory.

ana = nil


Conclusion

It's useful to know how memory management works in Swift to break strong reference to instance and to avoid any memory leaks in application.


Don’t hesitate to contact me if you have any questions or queries. Follow me on twitter @gurjitpt for any updates.

Thanks!


Share this article


Generic placeholder image

WRITTEN BY

Gurjit Singh

I’m Computer Science graduate and an iOS Engineer who writes about Swift and iOS development. Follow me on twitter @gurjitpt for more updates.


Next Posts

How to use enum in Swift Empty space for void

Enumerations (enum) enables you to write code in a type safe way. Enum is very useful while defining common type of values. You don't have to provide...

Mar 7, 2023 . 2 min read     Swift Enum

Read More »

Optional unwrapping syntax in Swift 5.7 Empty space for void

Optional unwrapping is one of the most used patterns in iOS development. Swift 5.7 introduces new features included a new way to unwrap optional values...

Jun 14, 2022 . 2 min read     Optional unwrapping

Read More »

Property observers in Swift Empty space for void

It's a common pattern or technique in various programming languages when we want to perform some action when a value is changed. Property ...

May 24, 2021 . 2 min read     Property Observers

Read More »