Swift Language Enums Basic enumerations


An enum provides a set of related values:

enum Direction {
    case up
    case down
    case left
    case right

enum Direction { case up, down, left, right }

Enum values can be used by their fully-qualified name, but you can omit the type name when it can be inferred:

let dir = Direction.up
let dir: Direction = Direction.up
let dir: Direction = .up

// func move(dir: Direction)...

obj.dir = Direction.up
obj.dir = .up

The most fundamental way of comparing/extracting enum values is with a switch statement:

switch dir {
case .up:
    // handle the up case
case .down:
    // handle the down case
case .left:
    // handle the left case
case .right:
    // handle the right case

Simple enums are automatically Hashable, Equatable and have string conversions:

if dir == .down { ... }

let dirs: Set<Direction> = [.right, .left]

print(Direction.up)  // prints "up"
debugPrint(Direction.up)  // prints "Direction.up"