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.

Thanks!


Next Posts

The ultimate guide to iOS Unit Testing with Swift and Xcode

Unit testing is a testing method where you can test “unit” of code whether it is working as you want or not. In Xcode, use XCTest framework to perform unit tests.

Jun 29, 2020 . 2 min read     Xcode Testing

Read More »

Custom Operators in Swift Empty space for void

Swift provides a very useful feature which is to define your own custom operators. It is a very confusing topic in the beginning but it is very powerful to use.It increases our code readability..

May 04, 2020 . 2 min read     Swift

Read More »

Protocol Extensions in Swift Empty space for void

A protocol can defines a set of methods that can be adopted by any class, but we can’t write code inside.On the other hand, extensions gives us the power to write code inside methods..

May 01, 2020 . 1 min read     Swift

Read More »