基本列舉

一個列舉提供了一組相關的值:

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

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

列舉值可以由其完全限定名稱使用,但可以在推斷時省略型別名稱:

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

比較/提取列舉值的最基本方法是使用 switch 語句:

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
}

簡單的列舉是自動 HashableEquatable 並具有字串轉換:

if dir == .down { ... }

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

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