是否可以优化代码片段?
Is it possible to optimize the code fragment?
我是 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 = ???
在一行中,只需使用默认枚举值中的原始值:
let country = MyEnum(rawValue: countryStr ?? defaultCountry.rawValue) ?? defaultCountry
其他方法:
var country = defaultCountry
if let validCountryStr = countryStr, let validCountryEnum = MyEnum(rawValue: validCountryStr) {
country = validCountryEnum
}
您可以在 Optional<String>
countryStr
上使用 flatMap(_:)。
let country = countryStr.flatMap({ MyEnum(rawValue: [=10=]) }) ?? defaultCountry
我是 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 = ???
在一行中,只需使用默认枚举值中的原始值:
let country = MyEnum(rawValue: countryStr ?? defaultCountry.rawValue) ?? defaultCountry
其他方法:
var country = defaultCountry
if let validCountryStr = countryStr, let validCountryEnum = MyEnum(rawValue: validCountryStr) {
country = validCountryEnum
}
您可以在 Optional<String>
countryStr
上使用 flatMap(_:)。
let country = countryStr.flatMap({ MyEnum(rawValue: [=10=]) }) ?? defaultCountry