是否可以优化代码片段?

时间:2017-12-28 11:49:31

标签: swift swift3

我是Swift的新手,我有以下代码片段,我觉得可以用更好的方式重写,但我无法实现。

    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
    }

有没有人知道如何让它变得更好,理想情况下是一行:

    let country = ???

2 个答案:

答案 0 :(得分:2)

你有一行,只需使用默认枚举值中的rawValue:

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

其他方法:

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

答案 1 :(得分:1)

您可以在Optional<String> countryStr上使用flatMap(_:)

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