1

I'm trying to accomplish a task which is passing an integer value to enum, and return a specific String for the passed in integrer.

I'm using enum because the integers are known and each of them has a meaning. I have done the following:

enum Genre: String {
    case 28 = "Action"
    case 12 = "Adventure"
    case 16 = "Animation"
    case 35 = "Comedy"
    case 80 = "Crime"
}

What I'm expecting: when passing one of the cases, I want to return the String association.

Please, if you have a question or need any further into, ask it in the comment.

3
  • Is there a reason not to use a dictionary? Commented Jun 2, 2017 at 8:47
  • Nope, any thoughts on what is the best practice to use it here? Commented Jun 2, 2017 at 8:48
  • @MEnnabah Better you go with dictionary Commented Jun 2, 2017 at 8:56

4 Answers 4

2

How about this

enum Genre: Int {
    case action = 28
    case adventure = 12
    case animation = 16
    case comedy = 35
    case crime = 80
}

And use it like this

// enum as string 
let enumName = "\(Genre.action)" // `action`

// enum as int value 
let enumValue = Genre.action.rawValue // 28

// enum from int
let action = Genre.init(rawValue: 28)

Hope it helps. Thanks.

Sign up to request clarification or add additional context in comments.

Comments

2

We can not have Int as an enum case name.
Try this:

enum Genre: Int {
case action = 28, adventure = 12, animation = 16, comedy = 35, crime = 80

  func getString() -> String {
    switch self {
    case .action: return "Action"
    case .adventure: return "Adventure"
    case .animation: return "Animation"
    case .comedy: return "Comedy"
    case .crime: return "Crime"
    }
  }
}

let gener = Genre.action
print(gener.getString())//"Action"

And if you only know integer value, do this:

let gener1 = Genre(rawValue: 12)!
print(gener1.getString())//"Adventure"

Comments

1
let Genre = [28:"action",
12: "adventure",
16: "animation",
35: "comedy",
80: "crime"]

Example use:
let retValue = Genre[28]//"action"

Here is playground demo:

enter image description here

Comments

1

I suggest creating a dictionary that achieves the mapping you need, and creating constants for your keys to use them.

You can start by creating a class called Constants and putting the following constants in it:

static let action = 28
static let adventure = 12
// ... The rest of your constants.

// Then create a dictionary that contains the values:
static let genre = [action : "Action", adventure : "Adventure"] // And so on for the rest of your keys.

Then you could access any value you need using that dictionary like so:

let actionString = Constants.genre[Constants.action]

Hope this helps.

Comments

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.