Enumerations and the Switch Statement

An enumeration is a type with a discrete set of values. Define an enum describing pies:

enum PieType {
    case Apple
    case Cherry
    case Pecan
}

let favoritePie = PieType.Apple

Swift has a powerful switch statement that, among other things, is great for matching on enum values:

let name: String
switch favoritePie {
case .Apple:
    name = "Apple"
case .Cherry:
    name = "Cherry"
case .Pecan:
    name = "Pecan"
}

The cases for a switch statement must be exhaustive: each possible value of the switch expression must be accounted for, whether explicitly or via a default: case. Unlike in C, Swift switch cases do not fall through – only the code for the case that is matched is executed. (If you need the ...

Get iOS Programming: The Big Nerd Ranch Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.