Created
May 25, 2016 15:34
-
-
Save oleksii-demedetskyi/824e0729b96721bde7f4d91e75231f64 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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