For the following code from the swift programming guide with deinitializers added by me, the resulting debug printout is the same whether the unowned keyword is used or not. The swift programming guide says that using unowned and implicitly unwrapped optionals is a way to break strong reference cycles when both properties that reference each other's class instances will never be nil. If both properties will never be nil, how is that different from a strong reference cycle? For example, why do we bother using the unowned keyword in this particular circumstance, especially when the debug readout shows that memory allocations are no different whether unowned is used or not?
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)
Debug readout:
Canada's capital city is called Ottawa
Ottawa is being deinitialized
Note: this was in a playground.