为什么我可以在对象的 deinit 方法被调用后访问它?

Why can I access an object after its deinit method has been called?

我从 Swift 指南的 Unowned References 部分复制了大部分代码,并在操场上 运行 它...

class Customer {
    let name: String
    var card: CreditCard?

    init(name: String) {
        self.name = name
    }
    deinit { print("\(name) is being “deinitialized") }
}

class CreditCard {
    let number: UInt64
    unowned let customer: Customer
    init(number: UInt64, customer: Customer) {
        self.number = number
        self.customer = customer
    }
    deinit { print("Card #\(number) is being deinitialized") }
}

var john: Customer?

john = Customer(name: "John Appleseed")
john!.card = CreditCard(number: 1234_5678_9012_3456, customer: john!)

var card = john!.card!

john = nil

card.customer.name

john 设置为 nil 结果...

"John Appleseed is being “deinitialized\n"

但是然后得到 name 属性 给出...

"John Appleseed"

因此,尽管已被取消初始化,客户实例仍然可以访问!

这不应该导致 nil 引用异常吗?它在指南中说...

Note also that Swift guarantees your app will crash if you try to access an unowned reference after the instance it references is deallocated. You will never encounter unexpected behavior in this situation. Your app will always crash reliably, although you should, of course, prevent it from doing so.

所以,我认为它一定没有被释放。然而,指南还说,

A deinitializer is called immediately before a class instance is deallocated.

代码在常规项目中按预期工作,而不是在 playground 中。