2017-12-28 2 views
1

저는 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 = ??? 

답변

1

Optional<String>countryStrflatMap(_:)을 사용할 수 있습니다.

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

당신이 그것을 가지고 한 줄에 그냥 기본 열거 값에서 rawValue를 사용

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

다른 접근 방식 :

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