Swift Language Enums Basic enumerations

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

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)...
move(Direction.up)
move(.up)

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"


Got any Swift Language Question?