Please use three backticks ``` to open and close a code block, so it makes it readable. I'll paste your code here for reference:
class Country {
init(name: String, capitalCity: City) {
self.name = name
self.capitalCity = capitalCity
}
var name: String
var capitalCity: City
}
class City {
let name: String
let country: Country
init(name: String, country: Country) {
self.name = name
self.country = country
}
}
var country = Country(name: "Canada", capitalCity: City(name: "Ottawa", country: capitalCity))
country.capitalCity = City(name: "Ottawa", country: country)
print("(country.name)'s capital city is called (country.capitalCity.name)")
The error seems to be that in the line when you're creating a country, that starts with var country = Country(..., you are passing a value called capitalCity to the country: parameter, but no capitalCity is defined before that line.
As written this is an impossible infinite recursive data structure. You need to break the cycle, e.g. this will do:
class Country {
init(name: String, capitalCity: City) {
self.name = name
self.capitalCity = capitalCity
}
var name: String
var capitalCity: City
}
class City {
let name: String
var country: Country!
init(name: String, country: Country!) {
self.name = name
self.country = country
}
}
func foo() {
let capitalCity = City(name: "Ottawa", country: nil)
let country = Country(name: "Canada", capitalCity: capitalCity)
capitalCity.country = country
print("(country.name)'s capital city is called (country.capitalCity.name)")
}
On top of that there's a retain cycle here which might or might not be a problem in your case:
if you create a country list once that's not a big deal, as it won't "leak" constantly, just stay in memory until app terminates.
if you creating countries / cities dynamically then:
either make one of the references weak (typically links to "parent" are made weak, so in this case the country field of the city class.
or break the link manually when you are about to delete the country.