Swift: Convert enum value to String?

The idiomatic interface for ‘getting a String’ is to use the CustomStringConvertible interface and access the description getter. You could specify the ‘raw type’ as String but the use of description hides the ‘raw type’ implementation; avoids string comparisons in switch/case and allows for internationalization, if you so desire. 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.

Leave a Comment