具有關聯值的列舉

列舉案例可以包含一個或多個有效負載關聯值 ):

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
}