StuartM
StuartM

Reputation: 6813

Swift enums: Getting enum value for string enum from int value

We are using enums for some basic data structures like this:

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

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

When we store the values in our database we store them as Ints/numbers. So for example the value for Industry might be 2 which would be Industry2.

How do I map the value 2, back to the relevant item in the enum? So I can retrieve the string value back?

Upvotes: 0

Views: 595

Answers (3)

Irfan
Irfan

Reputation: 5130

Industry is not represented in better way. You should pack industry name and code together in a better structure like this:

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

Now you could create a store class that can contain all industries. Through enum you are not representing it very well. For saving one thing and displaying other thing.

Now if you have to save you can industry.code

And if you want to display industry.name

Upvotes: 1

vacawama
vacawama

Reputation: 154513

Based on your setup you could do:

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

Upvotes: 0

JPetric
JPetric

Reputation: 3918

You can do this to have arbitrary industry names:

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"
        }
    }
}

Example of usage:

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

Upvotes: 3

Related Questions