I'mm trying to learn how ARC works exactly, so I read Swift ARC documentation and I followed the example that they provide in the document using playground:
class Person {
let name: String
weak 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 Appleseed")
unit4A = Apartment(unit: "4A")
john?.apartment = unit4A
unit4A?.tenant = john
john = nil
unit4A = nil
My question is why when I call Person
instance john
optional:
john?.apartment = unit4A
the object become deallocated, but when I call it force unwrapped:
john!.apartment = unit4A
it will not become deallocated.