Wednesday 21 August 2019

Swift non-optional, optional (?), and optional(!)


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 ("country deinit")
    }
}

class City {
    let name: String
    unowned let country: Country
    init(name: String, country: Country) {
        self.name = name
        self.country = country
    }
    deinit {
        print ("city deinit")
    }
}

var country: Country = Country(name: "Canada", capitalName: "Ottawa")
print ("country capital city is \(country.capitalCity.name)")

Why the exclamation mark is needed after City?

Without making it the variable optional, the code won't compile, because the country instance won't be considered fully initialised and therefore cannot be passed as an argument to initiate the city instance (country: self).

Can exclamation mark be replaced by question mark?

Yes, it can. But to access this property, it needs to be unwrapped. So country.capitalCity.name is to be replaced by country.capitalCity!.name. If we know for sure a property will never be null, it's better to be defined as City! rather than City?.

No comments:

Post a Comment