【问题标题】:Swift - Initialize enum from string in switch statementSwift - 在 switch 语句中从字符串初始化枚举
【发布时间】:2017-10-13 13:13:21
【问题描述】:

是否可以测试特定的枚举类型在切换字符串时是否可以通过rawValue来初始化,而不是使用if let?

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
}

谢谢!

【问题讨论】:

    标签: ios swift enums switch-statement


    【解决方案1】:

    如果我正确理解您想要什么,您可以使用 nil 合并运算符而不是 if let

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

    您可以根据需要添加尽可能多的其他枚举初始化。它将按顺序评估并返回第一个不是nil。如果都是nil,则返回nil。因此,它的行为与一系列if-let-else 完全相同。

    【讨论】:

    • 确实更好,不知道可以连续使用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-16
    • 1970-01-01
    • 1970-01-01
    • 2017-12-13
    • 1970-01-01
    相关资源
    最近更新 更多