Weak Reference in Swift

Level 5455 keystrokes

Person and Apartment refer to each other. Because tenant is weak, there is no strong reference cycle (retain cycle), so setting both variables to nil frees both objects and both deinit messages are printed.

Swift code

1class Person {
2 let name: String
// Strong reference from Person to Apartment
3 var apartment: Apartment?
4 init(name: String) { self.name = name }
// deinit runs when the instance is freed
5 deinit { print("\(name) deinitialized") }
6}
7
8class Apartment {
9 let unit: String
// weak does not keep the Person alive and becomes nil when it is freed
10 weak var tenant: Person?
11 init(unit: String) { self.unit = unit }
12 deinit { print("Apartment \(unit) deinitialized") }
13}
14
// Optionals so the variables can be set to nil later
15var person: Person? = Person(name: "Alice")
16var apt: Apartment? = Apartment(unit: "4A")
17
// Links the two objects in both directions
18person?.apartment = apt
19apt?.tenant = person
20
// Only the weak tenant still points to Alice, so she is freed: Alice deinitialized
21person = nil
// Alice's strong reference is gone too, so: Apartment 4A deinitialized
22apt = nil

Output

Alice deinitialized
Apartment 4A deinitialized
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Swift code and how often they appear.

  • :× 10
  • "× 8
  • (× 8
  • )× 8
  • =× 8
  • ?× 6
  • {× 6
  • }× 6
  • .× 4
  • \× 2

More Swift examples at level 5

← Swift typing practice