Reputation: 2513
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.
Upvotes: 1
Views: 500
Reputation: 6110
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.
Upvotes: 1
Reputation: 3404
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"
Upvotes: 2
Reputation: 33
let Genre = [28:"action",
12: "adventure",
16: "animation",
35: "comedy",
80: "crime"]
Example use:
let retValue = Genre[28]//"action"
Here is playground demo:
Upvotes: 1
Reputation: 19156
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.
Upvotes: 2