0
是否可以在切換字符串時測試某個特定枚舉類型是否可以由rawValue初始化,而不是使用if let?Swift - 從switch語句中的字符串初始化枚舉
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
堅持我的貨幣協議:
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
}
謝謝!
絕對更好,不知道它可以連續使用。 –