I have the following class that describes a country:
class Country: NSObject {
public var name: String
static let england = Country(name: "England")
static let scotland = Country(name: "Scotland")
static let allCountries = [england, scotland]
init(name: String) {
self.name = name
super.init()
}
convenience init?(named name: String) {
guard let country = Country.allCountries.filter( { $0.name == name } ).first else { return nil }
self.init(name: country.name)
}
}
To get the constant Country.england, I would use:
let england = Country.england
However, I want to be able to get this constant from a String using convenience init?(named name: String) as follows:
let england = Country(named: "England")
This seems a little clunky and this code initialises a new "england" instance rather than taking the static one.
Is there a more Swifty way of doing this? Ideally I'd like to just let self = country in the convenience init?(named name: String) function, but I get the error cannot assign to value: 'self' is immutable.
Thanks for any help.
.first(where: { $0.name == name } )rather than.filter( { $0.name == name } ).first