Swift Language Enums Enums with associated values


Enum cases can contain one or more payloads (associated values):

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

The payload must be provided when instantiating the enum value:

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

The switch statement can extract the associated value:

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

A single case extraction can be done using if case:

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

The guard case syntax can be used for later use extraction:

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

Enums with associated values are not Equatable by default. Implementation of the == operator must be done manually:

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