Skip to content

Instantly share code, notes, and snippets.

@aataraxiaa
Created June 28, 2016 10:31
Show Gist options
  • Save aataraxiaa/4114e34bdff308f49b0fa6ffddb65095 to your computer and use it in GitHub Desktop.
Save aataraxiaa/4114e34bdff308f49b0fa6ffddb65095 to your computer and use it in GitHub Desktop.
//: Playground - noun: a place where people can play
import UIKit
enum State {
case initial
case launched
case launchingWithLocation
case launchingWithoutLocation
case running
case backgrounded
case fromBackground
case fromBackgroundWithLocation
case fromBackgroundWithoutLocation
}
class ViewController: UIViewController {
private var state = State.initial {
didSet {
switch state {
case .launched:
// Do launch specific stuff, like attempt to get user's location
break
case .launchingWithLocation:
// Yeah! We have location, do stuff like make API calls
// We can also act depending on how we got to this state
switch oldValue {
case .launched:
// Do launch with location specific stuff
break
case .fromBackground:
// Do from background with location specific stuff
break
default:
break
}
case .launchingWithoutLocation:
// Sad, no location, but do some stuff anyway
break
case .running:
// Woohoo, we are fully set up and running so do cool stuff here
break
case .backgrounded:
// We are background, so do stuff like stop location updates
break
case .fromBackground:
// We are coming from the background, so do stuff like re-start location updates
break
case .fromBackgroundWithLocation:
// Yeah! We are back AND have location, do stuff like make API calls
break
default:
break
}
}
}
override func viewDidLoad() {
changeState()
}
}
typealias StateManager = ViewController
extension StateManager {
private func changeState(hasLocation: Bool = true, isBackgrounding: Bool = false) {
let compositeState = (state, hasLocation, isBackgrounding)
switch compositeState {
case (.launched, true, false):
state = .launchingWithLocation
case (.launched, false, false):
state = .launchingWithoutLocation
case (.launched, _, true):
state = .fromBackground
case (.launchingWithLocation, _, false):
state = .running
case (.running, _, true):
state = .backgrounded
case (.backgrounded, _, _):
state = .fromBackground
case (.fromBackground, true, _):
state = .fromBackgroundWithLocation
case (.fromBackground, false, _):
state = .fromBackgroundWithoutLocation
case (.fromBackgroundWithLocation, true, _):
state = .running
default:
break
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment