以下代码定义Person
和Apartment
。 Person
个实例可能拥有Apartment
,Apartment
可能拥有租户(Person
个实例)
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
现在执行以下代码以解除分配实例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")
}
问题: Xcode没有将tenant
属性设置为nil
(请参阅上图)
问题:我该如何解决?我已经尝试了IBM Swift SandBox上的代码并且效果很好,Xcode有错误吗?
非常感谢。
答案 0 :(得分:1)
游乐场是魔鬼的作品。在真实的应用程序项目中测试,而不是在游乐场中进行测试,您将看到它按预期工作。