Search code examples
stringenumsswift

Swift: Convert enum value to String?


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

Solution

  • 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"
    

    You can also assign custom strings to each case:

    enum Audience: String {
        case public = "The Public"
        case friends = "My Friends"
        case private = "Private Audience"
    }
    
    let audience = Audience.public.rawValue // "The 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.