Rob N
Rob N

Reputation: 16409

How to create enum from a String

In Swift 2, can you create an enum from a string?

enum Food : Int { case Pizza, Pancakes }
let str = "Pizza"
let food = Food(name:str)   // for example

That last line doesn't work, but I'm looking for something like it. Like in Java, you can say Food.valueOf("Pizza").

Edit: I can't use a String as a raw value.

Upvotes: 1

Views: 701

Answers (4)

Imanou Petit
Imanou Petit

Reputation: 92419

Ian's answer is great but, according to your needs, you may prefer an enum with a failable initializer:

enum Food: Int {

    case Pizza, Pancakes

    init?(name: String) {
        switch name {
        case "Pizza":       self = .Pizza
        case "Pancakes":    self = .Pancakes
        default:            return nil
        }
    }

}

let pizzaString = "Pizza"
let food = Food(name: pizzaString) // returns .Pizza (optional)
print(food?.rawValue) // returns 0 (optional)

Upvotes: 1

Ian
Ian

Reputation: 12768

You can create an initializer for the enum that takes a String as a parameter. From there, you switch over the string to set the value of self to a specific case like so:

enum Food: Int {
    case None, Pizza, Pancakes


    init(string: String) {
        switch string {
        case "Pizza":
            self = .Pizza
        default:
            self = .None
        }
    }
}

let foo = Food(string: "") // .None
let bar = Food(string: "Pizza") // .Pizza

Upvotes: 5

Ali Beadle
Ali Beadle

Reputation: 4516

Don't have a compiler around to check the details but something like:

enum Food { case Pizza="Pizza", Pancakes="Pancakes" }
let str = "Pizza"
let food = Food(rawValue:str)

Upvotes: 2

Duncan C
Duncan C

Reputation: 131418

You can set up Enums where the raw value is a string, and then create an enum by specifying a raw value. That's close to what you are asking for.

Upvotes: 1

Related Questions