I have worked with Swift book, example with using a weak reference to avoid strong reference cycles.
This is an example from the book. The issue that after setting john to nil the object should be deallocated and deinit should print
"John Appleseed is being deallocated".
But it doesn't work. I have an impression that despite weak reference Person object is still in memory. Is this Swift bug?
class Person {
let name: String
init(name: String) { self.name = name }
var apartment: Apartment?
deinit { print("\(name) is being deallocated.") }
}
class Apartment {
let unit: String
init(unit: String) { self.unit = unit }
weak var tenant: Person?
deinit { print("Apartment \(unit) is being deallocated.") }
}
var john: Person?
var unit4A: Apartment?
john = Person(name: "John Appleseed")
unit4A = Apartment(unit: "4A")
john!.apartment = unit4A
unit4A!.tenant = john
john = nil
Unfortunately, the approach with do block doesn't work with weak references. Playground somehow doesn't deallocate objects with reference cycle even with using weak. The sample of the code below, please verify.
class Person {
let name: String
init(name: String) { self.name = name }
var apartment: Apartment?
deinit { print("\(name) is being deallocated.") }
}
class Apartment {
let unit: String
init(unit: String) { self.unit = unit }
weak var tenant: Person?
deinit { print("Apartment \(unit) is being deallocated.") }
}
do {
var john: Person?
var unit4A: Apartment?
john = Person(name: "John Appleseed")
unit4A = Apartment(unit: "4A")
john!.apartment = unit4A
unit4A!.tenant = john
john = nil
}