Last active
February 11, 2017 10:40
-
-
Save flowinho/5985928f803d902b75fc69ee9ce26537 to your computer and use it in GitHub Desktop.
Question about extending Collections with mutable functions
This file contains 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
//: Playground - noun: a place where people can play | |
protocol Human { | |
var name:String { get } | |
} | |
protocol God { | |
var name:String { get } | |
} | |
protocol Soldier { | |
var hp:Int { get set } | |
var range:Int { get } | |
var canFly:Bool { get } | |
mutating func heal() | |
} | |
struct Player: Soldier, God { | |
var name = "PlayerKEK" | |
var hp = 150 | |
var range = 5 | |
} | |
struct Enemy:Soldier, Human { | |
var name = "Unknown Greek Hero" | |
var hp = 50 | |
var range = 1 | |
} | |
extension Soldier { | |
var canFly:Bool { return self is God } | |
mutating func heal() { | |
if self is God { | |
return self.hp += 300 | |
} | |
else { | |
return self.hp += 50 | |
} | |
} | |
} | |
extension Collection where Self.Iterator.Element: Soldier { | |
func totalAmountOfHP() -> Int { | |
var total = 0 | |
for item in self { | |
total += item.hp | |
} | |
return total | |
} | |
mutating func healAll() { | |
for var item in self { | |
item.heal() | |
} | |
} | |
} | |
var player = Player() | |
player.canFly // true | |
player.hp // 150 | |
player.heal() // Player | |
player.hp // 450 | |
var enemy = Enemy() | |
enemy.canFly // false | |
enemy.hp // 50 | |
enemy.heal() // Enemy | |
enemy.hp // 100 | |
var defenders = [Enemy(), Enemy()] | |
defenders.totalAmountOfHP() // 100 | |
defenders.healAll() | |
defenders.totalAmountOfHP() // 100 -- Why? | |
defenders.append(Enemy()) | |
defenders.totalAmountOfHP() // 150 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Im currently experimenting with extensions of the type
Collection
. Im still new to the field of adding mutable functions by extending protocols, so i dont understand why LOC 75 doesn't increase the amount of HP of all enemies.What am i doing wrong?
How to fix this?