0

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?

3 Answers 3

3

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"
Sign up to request clarification or add additional context in comments.

1 Comment

This is a good suggestive way to complete this. I've accepted the answer that works with the current setup and this is not overly different, possibly a better layout approach +1
1

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

1 Comment

Why T!? It's just bad practice to put ! everywhere in Swift code.
0

Based on your setup you could do:

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

1 Comment

You are correct, didn't think of using the allValues array but makes perfect sense

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.