I'm looking at the example from the “Unowned References and Implicitly Unwrapped Optional Properties” section of the book “The Swift Programming Language.”
Their example code is
class Country { let name: String let capitalCity: City! init(name: String, capitalName: String) { self.name = name self.capitalCity = City(name: capitalName, country: self) } } class City { let name: String unowned let country: Country init(name: String, country: Country) { self.name = name self.country = country } } This works if I want to deal exclusively with Countries and the only purpose of the City type is to be a capital of a Country. But what happens if I want to create a City?
This creates a runtime exception because no reference to the City's Country is retained since it is an unowned variable:
var chicago = City(name:"Chicago", country: Country(name: "USA", capitalName: "Washington DC")) chicago.country.name // Playground execution failed: error: Execution was interrupted, reason: EXC_BAD_ACCESS (code=EXC_I386_GPFLT). How would I allow something like this without creating a Strong Reference Cycle?