1

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.

Rob N
  • 15,024
  • 17
  • 92
  • 165

4 Answers4

5

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
Ian
  • 12,538
  • 5
  • 43
  • 62
  • As far as I know this is the best way using an Int enum rather than a String enum, but a better way may exist. – Ian Jun 09 '15 at 20:24
  • Oddly, my init(name:String) hides the the init(rawValue:Int), in project source, but not in playgrounds. http://stackoverflow.com/questions/30742475/why-initrawvalue-not-callable-for-some-enums – Rob N Jun 09 '15 at 20:46
  • @RobN we cannot achieve what you want via utilising reflection or rawValue. I think this answer is the best one . – M Abdul Sami Jun 09 '15 at 20:49
2

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)
Ali Beadle
  • 4,486
  • 3
  • 30
  • 55
  • OK, seen your edit that this is not what you need. I will leave it here as possible info for others though. – Ali Beadle Jun 13 '15 at 14:36
1

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.

Duncan C
  • 128,072
  • 22
  • 173
  • 272
1

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)
Imanou Petit
  • 89,880
  • 29
  • 256
  • 218