import UIKit class Example : UIView{ private var machine:StateMachine<Example>! enum TrafficLight{ case Stop, Go, Caution } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) machine = StateMachine(initialState: .Stop, delegate: self) } @IBAction func tappedGo(sender:AnyObject){ machine.state = .Go } @IBAction func tappedCaution(sender:AnyObject){ machine.state = .Caution } } extension Example : StateMachineDelegateProtocol{ typealias StateType = TrafficLight func shouldTransitionFrom(from: StateType, to: StateType) -> Should<StateType> { switch (from, to){ case (.Stop, .Go), (.Caution, .Stop): return .Continue case (.Go, .Caution): return .Redirect(.Stop) default: return .Abort } } func didTransitionFrom(from: StateType, to: StateType) { switch to{ case .Stop: backgroundColor = UIColor.redColor() case .Go: backgroundColor = UIColor.greenColor() case .Caution: backgroundColor = UIColor.yellowColor() } } }