我正在通过Swift语言参考,并试图了解如何实现弱和无主引用。下面的代码片段在书中,除了我在初始化器中添加了println()语句。当我执行它时,我确认对象已初始化,但它们没有取消初始化。
class Customer {
let name: String
var card: CreditCard?
init(name: String) {
self.name = name
println("Customer init")
}
deinit { println("Customer deinit") }
}
class CreditCard {
let number: UInt64
unowned let customer: Customer
init (number: UInt64, customer: Customer) {
self.number = number
self.customer = customer
println("CreditCard init")
}
deinit { println("Card #\(number) deinit") }
}
var john: Customer?
john = Customer(name: "John Appleseed")
john!.card = CreditCard(number: 540530453, customer: john!)
john = nil
我的控制台输出是:
Customer init
CreditCard init
这对我来说意味着对象正在初始化,但不是取消初始化。为什么Swift坚持引用并且不让对象被破坏?