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
}
谢谢!
绝对更好,不知道它可以连续使用。 –