Enumeration as state machine
An enumeration is an example of a state machine, meaning it can only ever be a single enumeration value at a time, never more. The friendly traffic light illustrates this concept well:
enum TrafficLight {
case red, yellow, green
}
let trafficLight = TrafficLight.red
A working traffic light will never be red and green simultaneously. You can observe this state machine behavior in other modern devices that follow a predetermined sequence of actions in response to a sequence of events. Examples of state machines include:
- Vending machines that dispense soda when the customer deposits the proper amount of money
- Elevators that drop riders off at upper floors before going down
- Combination locks that require combination numbers in the proper order
To operate as expected, these devices depend on an enumeration’s guarantee that it will only ever be in one state at a time.