create a finite state machine in swift

To create a finite state machine (FSM) in Swift, we first define the states and the events that can occur in each state. Next, we define the transitions between states that occur when those events occur.

Here's an example implementation of an FSM in Swift that models a simple traffic light.

main.swift
enum TrafficLightState {
    case green
    case yellow
    case red
}

enum TrafficLightEvent {
    case timerExpired
}

class TrafficLight {
    private var state: TrafficLightState
    
    init() {
        state = .green
    }
    
    func handleEvent(event: TrafficLightEvent) {
        switch (state, event) {
        case (.green, .timerExpired):
            state = .yellow
        case (.yellow, .timerExpired):
            state = .red
        case (.red, .timerExpired):
            state = .green
        default:
            break
        }
    }
}
563 chars
31 lines

In this implementation, we define the TrafficLightState enumeration to represent the states of the traffic light (green, yellow, and red). We also define the TrafficLightEvent enumeration to represent the event that can occur in each state (a timer expiring).

Then, we define the TrafficLight class that contains the FSM. The handleEvent function takes an event as its argument, and based on the current state and the event that occurred, it updates the state of the traffic light accordingly.

With this implementation, we can create a TrafficLight instance and simulate the traffic light changing states like so:

main.swift
let trafficLight = TrafficLight()

trafficLight.handleEvent(event: .timerExpired) // current state is now yellow
trafficLight.handleEvent(event: .timerExpired) // current state is now red
trafficLight.handleEvent(event: .timerExpired) // current state is now green
265 chars
6 lines

Of course, this is a simplistic example, and in practice, FSMs can be much more complex. But the basic idea is the same: define the states, events, and transitions, and let the FSM handle the logic of transitioning between states.

gistlibby LogSnag