Swift: Convert enum value to String?

ma11hew28 picture ma11hew28 · Jul 11, 2014 · Viewed 115.3k times · Source

Given the following enum:

enum Audience {
    case Public
    case Friends
    case Private
}

How do I get the string "Public" from the audience constant below?

let audience = Audience.Public

Answer

GoZoner picture GoZoner · Jul 12, 2014

The idiomatic interface for 'getting a String' is to use the CustomStringConvertible interface and access the description getter. Define your enum as:

enum Foo : CustomStringConvertible {
  case Bing
  case Bang
  case Boom
  
  var description : String { 
    switch self {
    // Use Internationalization, as appropriate.
    case .Bing: return "Bing"
    case .Bang: return "Bang"
    case .Boom: return "Boom"
    }
  }
}

In action:

 > let foo = Foo.Bing
foo: Foo = Bing
 > println ("String for 'foo' is \(foo)"
String for 'foo' is Bing

Updated: For Swift >= 2.0, replaced Printable with CustomStringConvertible

Note: Using CustomStringConvertible allows Foo to adopt a different raw type. For example enum Foo : Int, CustomStringConvertible { ... } is possible. This freedom can be useful.