'self' used before all stored properties are initialized

Ultrasaurus picture Ultrasaurus · Dec 26, 2015 · Viewed 24.9k times · Source

I'm working through a learn-swift playground and upgrading it to Swift 2.0 as I learn the language. The following code (which likely worked with prior versions of Swift) now generates two errors: "'self' used before all stored properties are initialized" and "Constant 'self.capitalCity' used before initialized"

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
    }
}

reading an answer to a similar question I see that I can change let capitalCity: City! to var capitalCity: City! and the syntax error is resolved.

I realize that in this contrived example a country's capital city can change, so that would be fine, but what if there were a case where the value really was a constant...

Is there any way to resolve the syntax error while keeping capitalCity a constant?

Answer

Qbyte picture Qbyte · Dec 26, 2015

In this case I would suggest you to make the property a variable but hiding it (make it seem like a constant) through a computed property:

class Country {
    let name: String

    private var _capitalCity: City!
    var capitalCity: City {
        return _capitalCity
    }

    init(name: String, capitalName: String) {
        self.name = name
        self._capitalCity = City(name: capitalName, country: self)
    }
}