Skip to content

Instantly share code, notes, and snippets.

@rjchatfield
Created September 8, 2015 15:54
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 rjchatfield/d78cca1bf7b02323bad9 to your computer and use it in GitHub Desktop.
Save rjchatfield/d78cca1bf7b02323bad9 to your computer and use it in GitHub Desktop.
Explaining Flux data flow in Swift
// Line 109 is where the magic is!
import Foundation
import XCPlayground
func setInterval(seconds interval: Int, f: ()->()) {
let delta = Int64(1) * Int64(NSEC_PER_SEC)
let time = dispatch_time(DISPATCH_TIME_NOW, delta)
dispatch_after(time, dispatch_get_main_queue(), {
f()
setInterval(seconds: interval, f: f)
});
}
XCPSetExecutionShouldContinueIndefinitely()
typealias StateType = Int
typealias ViewType = String
typealias DiffType = String
enum Action {
case Increment
case Decrement
}
struct StateDS {
let value: StateType
}
struct ViewDS {
let value: ViewType
}
struct DiffDS {
let value: DiffType
}
var currentStateDS: StateDS = StateDS(value: 0)
var currentViewDS: ViewDS = ViewDS(value: "")
func cache(f: StateType -> StateType) -> StateDS {
currentStateDS = StateDS(value: f(currentStateDS.value))
return currentStateDS;
}
func state(action: Action) -> StateDS {
switch action {
case .Increment: return cache { $0 + 1 }
case .Decrement: return cache { $0 - 1 }
}
}
func view(state: StateDS) -> ViewDS {
let jsx_is_amazing = "---------\n--- \(state.value) ---\n---------"
return ViewDS(value: jsx_is_amazing)
}
func diff(view: ViewDS) -> DiffDS {
// VIRTUAL DOM IS AMAZING
currentViewDS = view
return DiffDS(value: view.value)
}
func draw(diff: DiffDS) {
for _ in 1...20 {
print("")
}
print(diff.value)
}
infix operator => {
associativity left
}
func => (lhs: Action, rhs: (Action) -> StateDS) -> StateDS {
return rhs(lhs)
}
func => (lhs: StateDS, rhs: (StateDS) -> ViewDS) -> ViewDS {
return rhs(lhs)
}
func => (lhs: ViewDS, rhs: (ViewDS) -> DiffDS) -> DiffDS {
return rhs(lhs)
}
func => (lhs: DiffDS, rhs: (DiffDS) -> ()) -> () {
return rhs(lhs)
}
extension Action {
func produceNewState () -> StateDS {
return state(self)
}
}
extension StateDS {
func produceNewView() -> ViewDS {
return view(self)
}
}
extension ViewDS {
func diffView() -> DiffDS {
return diff(self)
}
}
extension DiffDS {
func drawDiff() -> () {
draw(self)
}
}
Action.Increment
.produceNewState()
.produceNewView()
.diffView()
.drawDiff()
func trigger(action: Action) -> () {
action => state => view => diff => draw
}
setInterval(seconds: 1) {
trigger(.Increment)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment