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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…