基本枚举

一个枚举提供了一组相关的值:

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"