Skip to content

Instantly share code, notes, and snippets.

@stepanhruda
Created August 2, 2016 19:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stepanhruda/77c62dfdeb821f597f7ccf14f1042be3 to your computer and use it in GitHub Desktop.
Save stepanhruda/77c62dfdeb821f597f7ccf14f1042be3 to your computer and use it in GitHub Desktop.
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