具有关联值的枚举

枚举案例可以包含一个或多个有效负载关联值 ):

enum Action {
    case jump
    case kick
    case move(distance: Float)  // The "move" case has an associated distance
}

在实例化枚举值时必须提供有效负载:

performAction(.jump)
performAction(.kick)
performAction(.move(distance: 3.3))
performAction(.move(distance: 0.5))

switch 语句可以提取相关值:

switch action {
case .jump:
    ...
case .kick:
    ...
case .move(let distance):  // or case let .move(distance):
    print("Moving: \(distance)") 
}

使用 if case 可以完成单个案例提取:

if case .move(let distance) = action {
    print("Moving: \(distance)") 
}

guard case 语法可用于以后的使用提取:

guard case .move(let distance) = action else {
    print("Action is not move")
    return
}

默认情况下,具有关联值的枚举不是 Equatable== 运算符的实现必须手动完成:

extension Action: Equatable { }

func ==(lhs: Action, rhs: Action) -> Bool {
    switch lhs {
    case .jump: if case .jump = rhs { return true }
    case .kick: if case .kick = rhs { return true }
    case .move(let lhsDistance): if case .move (let rhsDistance) = rhs { return lhsDistance == rhsDistance }
    }
    return false
}