Skip to content

Instantly share code, notes, and snippets.

@qwzybug
Created November 4, 2014 23:47
Show Gist options
  • Select an option

  • Save qwzybug/f1ddcbb674f1f1cd63c5 to your computer and use it in GitHub Desktop.

Select an option

Save qwzybug/f1ddcbb674f1f1cd63c5 to your computer and use it in GitHub Desktop.
Experimenting with using variable enums as state machines, inspired by http://github.com/schwa/SwiftStateMachine
// Playground - noun: a place where people can play
import UIKit
enum Turnstile {
case Locked
case Unlocked
mutating func push() -> Bool {
switch self {
case .Unlocked:
self = .Locked
return true
default:
return false
}
}
mutating func coin() -> Bool {
switch self {
case .Locked:
self = .Unlocked
return true
default:
return false
}
}
}
class SubwayStation {
var turnstile: Turnstile = .Locked {
willSet {
switch (turnstile, newValue) {
case (.Unlocked, .Locked):
println("Turnstile is locking!")
case (.Locked, .Unlocked):
println("Turnstile is unlocking!")
default:
break
}
}
}
func enter() {
if turnstile.push() {
println("Entered the station!")
}
else {
println("Have to pay first!")
}
}
func pay() {
if turnstile.coin() {
println("Thank you for your patronage!")
}
else {
println("Fare already paid! Please enter.")
}
}
}
var MontgomeryStreet = SubwayStation()
MontgomeryStreet.enter()
// => Have to pay first!
MontgomeryStreet.pay()
// => Turnstile is unlocking!
// Thank you for your patronage!
MontgomeryStreet.enter()
// => Turnstile is locking!
// Entered the station!
MontgomeryStreet.pay()
// => Turnstile is unlocking!
// Thank you for your patronage!
MontgomeryStreet.pay()
// => Fare already paid! Please enter.
MontgomeryStreet.pay()
// => Fare already paid! Please enter.
MontgomeryStreet.enter()
// => Turnstile is locking!
// Entered the station!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment