Skip to content

Updating an enum value

Giuseppe Lanza edited this page Oct 6, 2019 · 1 revision

Currently to update an associated value of an enum value is very verbose.

Let's take in consideration a simple example:

enum State: CaseAccessible {
    case count(Int)
    case error
}

This code change the value of an enum instance when this represent a count case:

func changeCount(_ state: inout State, to newValue: Int) {
    guard case .count = state else { return }
    state = State.count(newValue)
}

func incrementCount(_ state: inout State, by increment: Int) {
    guard case let .count(value) = state else { return }
    state = State.count(value + increment)
}

With EnumKit this example becomes

func changeCount(_ state: inout State, to newValue: Int) -> State {
    state[case: State.count] = newValue
}

func incrementCount(_ state: inout State, by increment: Int) {
    state[case: State.count, default: 0] += increment
}

The case subscript can in fact update the associated value of an enum case, when the instance actually match the case pattern.

var state: State = .count(0)

state[case: State.count] = 1
print(state) //State.count(1)

state[case: State.count, default: 0] += 1
print(state) //State.count(2)
Clone this wiki locally