【问题标题】:Swift enums: Getting enum value for string enum from int valueSwift枚举:从int值获取字符串枚举的枚举值
【发布时间】:2016-12-12 13:37:02
【问题描述】:

我们将枚举用于一些基本的数据结构,如下所示:

enum Industry: String {
    case Industry1 = "Industry 1", Industry2 = "Industry 2", Industry3 = "Industry 3"

     static let allValues = [Industry1, Industry2, Industry3]
}

当我们将值存储在数据库中时,我们将它们存储为整数/数字。例如,Industry 的值可能是 2,即 Industry2。

如何将值 2 映射回枚举中的相关项?这样我就可以找回字符串值了?

【问题讨论】:

    标签: swift string enums


    【解决方案1】:

    您可以这样做以获得任意行业名称:

    enum Industry: Int {
        case Industry1 = 1, Industry2, Industry3
    
        static let allValues = [Industry1, Industry2, Industry3]
    
        func industryName() -> String {
            switch self {
            case .Industry1: return "Industry A"
            case .Industry2: return "Industry B"
            case .Industry3: return "Industry C"
            }
        }
    }
    

    使用示例:

    let industry = Industry(rawValue: 2)
    industry?.industryName() // prints "Industry B"
    

    【讨论】:

    • 这是一个很好的建议方式来完成这个。我已经接受了适用于当前设置的答案,这并没有太大的不同,可能是更好的布局方法 +1
    【解决方案2】:

    行业没有以更好的方式呈现。您应该将行业名称和代码打包成一个更好的结构,如下所示:

    struct Industry {
        var name: String
        var code: Int
    }
    

    现在您可以创建一个可以包含所有行业的商店类。 通过枚举,您不能很好地表示它。用于保存一件事并显示另一件事。

    现在如果你必须保存你可以industry.code

    如果你想显示industry.name

    【讨论】:

    • 为什么是T!?在 Swift 代码中随处放置 ! 是一种不好的做法。
    【解决方案3】:

    根据您的设置,您可以:

    let n = 2
    let stringValue = Industry.allValues[n - 1].rawValue
    

    【讨论】:

    • 你是对的,没有想到使用 allValues 数组,但很有意义
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-12
    • 1970-01-01
    • 2014-02-02
    • 1970-01-01
    • 1970-01-01
    • 2011-10-09
    相关资源
    最近更新 更多