0

我正在研究 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 坚持引用而不让对象被销毁?

4

0 回答 0