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
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.