Nick
Nick

Reputation: 3435

Is it possible to optimize the code fragment?

I am new to Swift, and I have the following code fragment which I feel can be re-written in a more nice way, but I cannot realize how.

    let defaultCountry: MyEnum = ....
    let countryStr: String? = ....

    // How can I optimize the fragment below?
    let country: MyEnum
    if let countryStr = countryStr {
        country = MyEnum(rawValue: countryStr) ?? defaultCountry
    }
    else {
        country = defaultCountry
    }

Do anyone have an idea how to make it better, ideally in one line:

    let country = ???

Upvotes: 1

Views: 46

Answers (2)

Daniel Illescas
Daniel Illescas

Reputation: 6126

There you have it in one line, just use the rawValue from the default enum value:

let country = MyEnum(rawValue: countryStr ?? defaultCountry.rawValue) ?? defaultCountry

Other approach:

var country = defaultCountry
if let validCountryStr = countryStr, let validCountryEnum = MyEnum(rawValue: validCountryStr) {
    country = validCountryEnum
}

Upvotes: 2

Yannick
Yannick

Reputation: 3278

You can use flatMap(_:) on your Optional<String> countryStr.

let country = countryStr.flatMap({ MyEnum(rawValue: $0) }) ?? defaultCountry

Upvotes: 1

Related Questions