Skip to content
Tom Ryan edited this page Jun 3, 2015 · 2 revisions

Enumerations

Enumerations can be quite powerful in Swift. In Objective-C (and C of course), they provide a space for a delimited set of (usually) integer-based values.

While this can also be true in Swift, when set up this way, Enums can also be very different.

Enums can be their own type

enum Direction {
    case North, South, East, West
}
var myDirection = Direction.North
//This will fail because Direction doesn't have a defined type
//myDirection.rawValue

In Objective-C, one could assume that Direction.North == 0. This is not the case in Swift for the above enum Direction. Direction.North (or whatever) does not have an inherent value.

Enums can have (raw) values

enum DirectionString : String {
    case North = "North"
    case South = "South"
    case East = "East"
    case West = "West"
}

var myDirection = DirectionString.North
myDirection.rawValue // Evaluates to "North"

enum DirectionPosition : Float {
    case North = 0.0
    case South = 180.0
    case East = 90.0
    case West = 270.0
}

Enum can have (Associated) values

enum CustomDirection {
    case North(DirectionString, DirectionPosition)
    case South(DirectionString, DirectionPosition)
    case East(DirectionString, DirectionPosition)
    case West(DirectionString, DirectionPosition)
}

let myCustomDirection = CustomDirection(DirectionString.North, DirectionPosition.North)

switch myCustomDirection {
    case CustomDirection.North(let myDescription, _):
        println("Hey I'm at \(myDescription.rawValue)!)"
    default:
        println("I didn't find north")

or

struct Personage {
    var firstName : String
    let lastName : String
}

The eagle-eyed amongst you notice I didn't have to create an init for the Personage struct!

var tom = Personage(firstName: "Tom", lastName: "Sawyer")
var dick = Personage(firstName: "Dick", lastName: "Tracy")
var harry = Personage(firstName: "Harry", lastName: "Houdini")

enum PersonableDirection {
    case North(Direction, Personage?)
}

var tomDirection = PersonableDirection.North(Direction.North, tom)

switch tomDirection {
case PersonableDirection.North(_, let person): // '_' means I don't care about that value.
    println(person!.firstName)
}

The Playground in this repo has a fuller example with mixed associated values, and shows how to bind them to a UITableView.

Enums with Associated Values cannot also have their own type

enum BadDirection : String {
    case North(Direction) = "Bad North"
}