Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Turnstyle
struct BrokenTurnstyle {
private let previousState: WorkingTurnstyle
func machineRepairDidComplete() -> WorkingTurnstyle {
return previousState
}
}
struct WorkingTurnstyle {
private(set) var state: State = .Locked(credit: 0)
private static let farePrice: UInt = 50
enum State {
case Locked(credit: UInt)
case Unlocked
}
enum Command {
case SoundAlarm
case CloseDoors
case OpenDoors
}
mutating func insertCoin(value: UInt) -> Command? {
switch state {
case .Locked(let credit):
let newCredit = credit + value
if newCredit >= WorkingTurnstyle.farePrice {
state = .Unlocked
return .OpenDoors
} else {
return nil
}
case .Unlocked:
return nil
}
}
mutating func admitPerson() -> Command? {
switch state {
case .Unlocked:
state = .Locked(credit: 0)
return .CloseDoors
case .Locked:
return .SoundAlarm
}
}
func machineDidFail() -> BrokenTurnstyle {
return BrokenTurnstyle(previousState: self)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment