Swift: Convert enum value to String?
Solution 1:
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.
Solution 2:
Not sure in which Swift version this feature was added, but right now (Swift 2.1) you only need this code:
enum Audience : String {
case public
case friends
case private
}
let audience = Audience.public.rawValue // "public"
When strings are used for raw values, the implicit value for each case is the text of that case’s name.
[...]
enum CompassPoint : String { case north, south, east, west }
In the example above, CompassPoint.south has an implicit raw value of "south", and so on.
You access the raw value of an enumeration case with its rawValue property:
let sunsetDirection = CompassPoint.west.rawValue // sunsetDirection is "west"
Source.
Solution 3:
In swift 3, you can use this
var enumValue = Customer.Physics
var str = String(describing: enumValue)
from Swift how to use enum to get string value