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 Apartment3 var apartment: Apartment?4 init(name: String) { self.name = name } // deinit runs when the instance is freed5 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 freed10 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 later15var person: Person? = Person(name: "Alice")16var apt: Apartment? = Apartment(unit: "4A")17 // Links the two objects in both directions18person?.apartment = apt19apt?.tenant = person20 // Only the weak tenant still points to Alice, so she is freed: Alice deinitialized21person = nil// Alice's strong reference is gone too, so: Apartment 4A deinitialized22apt = nilOutput
Alice deinitialized Apartment 4A deinitialized
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