Created
April 17, 2019 11:49
-
-
Save nuclearace/53c0df2b621450e55689c18d249593ca 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
| protocol Player { | |
| var name: String { get } | |
| var hitpoints: Int { get set } | |
| } | |
| protocol DeathWathable { | |
| func playerDied(_ player: Player) | |
| } | |
| @propertyDelegate | |
| class DeathAlerter<Value: Player> { | |
| var watchers = [DeathWathable]() | |
| init(initialValue: Value) { | |
| self.value = initialValue | |
| } | |
| var value: Value { | |
| didSet { | |
| guard value.hitpoints <= 0 else { | |
| return | |
| } | |
| for watcher in watchers { | |
| watcher.playerDied(value) | |
| } | |
| } | |
| } | |
| func addWatcher(_ watcher: DeathWathable) { | |
| self.watchers.append(watcher) | |
| } | |
| } | |
| struct P: Player { | |
| let name: String | |
| var hitpoints = 100 { | |
| didSet { | |
| if hitpoints < 0 { | |
| hitpoints = 0 | |
| } | |
| } | |
| } | |
| init(name: String, hitpoints: Int = 100) { | |
| self.name = name | |
| self.hitpoints = hitpoints | |
| } | |
| } | |
| class Arena { | |
| @DeathAlerter var p1 = P(name: "Player 1") | |
| @DeathAlerter var p2 = P(name: "Player 1") | |
| } | |
| class EventBoard: DeathWathable { | |
| func playerDied(_ player: Player) { | |
| print("\(player.name) died") | |
| } | |
| } | |
| let eventBoard = EventBoard() | |
| let arena = Arena() | |
| arena.$p1.addWatcher(eventBoard) | |
| arena.$p2.addWatcher(eventBoard) | |
| arena.p1.hitpoints -= 100 // Will print Player 1 Died |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment