2017-10-13 7 views
0

letを使用するのではなく、文字列を切り替えるときに、特定の列挙型をrawValueで初期化できるかどうかテストできますか?Swift - switch文の文字列からenumを初期化する

switch currency { 
case let fiatCurrency as Fiat: 
    return getFiatFormatting(for: value, fiatCurrency: fiatCurrency) 
case let blockchain as Blockchain: 
    return getCryptoFormatting(for: value, blockchain: blockchain) 
case let token as Token: 
    return getTokenFormatting(for: value, token: token) 
default: 
    return nil 
} 

ありがとう:

static func getCurrency(from code: String) -> Currency? { 
    if let fiatCurrency = Fiat(rawValue: code) { 
     return fiatCurrency 
    } else if let cryptoCurrency = Blockchain(rawValue: code) { 
     return cryptoCurrency 
    } else { 
     return nil 
    } 
} 

これはcurrencyは私の通貨プロトコルに準拠キャストを入力するために同様のかもしれません!

答えて

0

正しく理解したら、if letの代わりにnil合体演算子を使用できます。

static func getCurrency(from code: String) -> Currency? { return Fiat(rawValue: code) ?? Blockchain(rawValue: code) }

必要な数の他の可能な列挙型の初期化を追加することができます。それは順序で評価し、それがnilではないことを最初に返します。すべてがnilの場合、nilを返します。したがって、一連のif-let-elseとまったく同じ動作をします。

+0

間違いなく、それが連続して使用できることに気付かなかった。 –

関連する問題