Weak, Strong and Unowned in Swift

Weak and unowned keywords are used to define weak and unowned references to objects. A weak reference is a reference to an object that doesn’t prevent the object from being deallocated by the automatic reference counting (ARC) system. An unowned reference is a reference to an object that is assumed to always exist and therefore doesn’t prevent the object from being deallocated. Below is an example of how you might use weak and unowned references in Swift:

class Person { 

  let name: String 
  var apartment: Apartment? 

  init(name: String) { 
    self.name = name 

  deinit { 
    print("\(name) is being deinitialized") 

class Apartment { 

  let unit: String 
  weak var tenant: Person? 

  init(unit: String) { 
    self.unit = unit 
  deinit { 
    print("Apartment \(unit) is being deinitialized") 

var john: Person? 
var unit4A: Apartment? 
john = Person(name: "John") 
unit4A = Apartment(unit: "4A") 
john!.apartment = unit4A 
unit4A!.tenant = john 
john = nil 
unit4A = nil

In this example, we have two classes: Person and Apartment. A Person has a name and an optional Apartment, and an Apartment has a unit number and an optional Person (the tenant). Then we create a Person named “John” and an Apartment with the unit number “4A”. We then assign the Apartment to the Person’s apartment property and the Person to the Apartment's ‘tenant’ property. We used a weak reference for the ‘tenant‘ property and an unowned reference for the apartment property, the reference counts of both objects remain the same, even though they reference each other. When we set both objects to nil, they are deallocated by ARC, and the deinit methods are called to print a message.

Also read: How to Separate UITableView/UICollectionView DataSource from a View Controller in Swift