对于我添加的带有反初始化器的 swift 编程指南中的以下代码,无论是否使用 unowned 关键字,生成的调试打印输出都是相同的。swift 编程指南说,当引用彼此的类实例的两个属性永远不会为零时,使用无主和隐式展开的选项是一种打破强引用循环的方法。如果这两个属性都不会为零,那与强引用循环有何不同?例如,为什么我们要在这种特殊情况下使用 unowned 关键字,尤其是当调试读数显示无论是否使用 unowned 内存分配都没有区别时?
class Country {
let name: String
var capitalCity: City!
init(name: String, capitalName: String) {
self.name = name
self.capitalCity = City(name: capitalName, country: self)
}
deinit {print("\(name) is being deinitialized")}
}
class City {
let name: String
unowned let country: Country
init(name: String, country: Country) {
self.name = name
self.country = country
}
deinit {print("\(name) is being deinitialized")}
}
var canada = Country(name: "Canada", capitalName: "Ottawa")
print("\(canada.name)'s capital city is called \(canada.capitalCity.name)")
canada.capitalCity = City(name: "Vancouver", country: canada)
调试读数:
Canada's capital city is called Ottawa
Ottawa is being deinitialized
注意:这是在操场上。