Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Unowned References in Swift
Written by Team Kodeco

Unowned references are similar to weak references in that they don’t increase the reference count of the referenced object.

However, unlike weak references, unowned references aren’t optional and always expect to have a value.

Consider an example where you have two classes, Person and Home. A person can live in a home, but a home can exist without a person. In this case, you would use an unowned reference for the home property in Person, because it’s assumed that the home will always exist, but a person may not.

class Person {
  var name: String
  unowned var home: Home

  init(name: String, home: Home) {
    self.name = name
    self.home = home
  }

  deinit {
    print("\(name) is no longer living in the home.")
  }
}

class Home {
  var address: String

  init(address: String) {
    self.address = address
  }

  deinit {
    print("Home at \(address) has been demolished.")
  }
}

var home: Home? = Home(address: "123 Main St")
var john: Person? = Person(name: "John", home: home!)

john = nil
// Prints "John is no longer living in the home."

home = nil
// Prints "Home at 123 Main St has been demolished.""

In this example, when the john variable is set to nil, the Person instance is deinitialized and its deinit message is printed, but the Home instance isn’t affected because it’s an unowned reference. When the home variable is set to nil, there are no more references to it, so the Home instance is deinitialized and its deinit message is printed.

It’s important to remember that using an unowned reference assumes that the referenced object will always exist. If the referenced object is deinitialized before the object holding the unowned reference, accessing the unowned reference will cause a runtime error. So, it’s important to be careful when using unowned references and ensure that the referenced object will always exist.

© 2024 Kodeco Inc.