Skip to content

Instantly share code, notes, and snippets.

@oleksii-demedetskyi
Last active May 25, 2016 15:33
Show Gist options
  • Save oleksii-demedetskyi/f9c27ae72aa8d71d8239ce970972b3d8 to your computer and use it in GitHub Desktop.
Save oleksii-demedetskyi/f9c27ae72aa8d71d8239ce970972b3d8 to your computer and use it in GitHub Desktop.
struct Counter {
var value = 0
enum Event { case Increment, Decrement }
mutating func handle(event: Event) {
switch event {
case .Increment: value += 1
case .Decrement: value -= 1
}
}
struct Actions {
let dispatch: Event -> ()
func increment() { dispatch(.Increment) }
func decrement() { dispatch(.Decrement) }
}
}
struct TwoCounters {
var left = Counter()
var right = Counter()
enum Event { case Left(Counter.Event), Right(Counter.Event) }
mutating func handle(event: Event) {
switch event {
case .Left(let event): left.handle(event)
case .Right(let event): right.handle(event)
}
}
struct Actions {
let left: Counter.Actions
let right: Counter.Actions
let both: Counter.Actions
init(dispatch: Event -> ()) {
self.left = Counter.Actions { dispatch(.Left($0)) }
self.right = Counter.Actions { dispatch(.Right($0)) }
self.both = Counter.Actions { event in
dispatch(.Left(event))
dispatch(.Right(event))
}
}
}
}
var twoCounters = TwoCounters()
let actions = TwoCounters.Actions { twoCounters.handle($0) }
print(twoCounters)
actions.left.increment()
print(twoCounters)
actions.right.increment()
print(twoCounters)
actions.both.decrement()
print(twoCounters)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment