Search code examples
swiftmemory-managementxcode7weak-references

Property is unable to set to nil via weak reference


The following code defines Person and Apartment. Person instance may own an Apartment, Apartment may have a tenant(Person instance)

class Person {
    let name: String
    init(name: String) { self.name = name }
    var apartment: Apartment?
    deinit { print("\(name) is being deinitialized") }
}

class Apartment {
    let unit: String
    init(unit: String) { self.unit = unit }
    weak var tenant: Person?
    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

The code snippet above can also be represented graphically as follows. enter image description here

Now the following code is executed to deallocated instance john

john = nil

if let per = unit4A!.tenant {
    print("\(per.name) is a ghost person") \\This line is prented out, isn't it already a set with `nil`?
} else {
    print("all nil dude")
}

enter image description here

Problem: Xcode doesn't set tenant property to nil (please see the last figure)

Question: How can I fix it? I've tried the code on IBM Swift SandBox and it works well, Xcode has a bug?

Many thanks.

enter image description here


Solution

  • Playgrounds are the work of the devil. Test in a real app project, not a playground, and you will see that this works as you expect.