我正在学习面向协议的编程,我有一个敌人和玩家的模型,玩家可以像这样伤害敌人:
protocol Targetable {
func takeDamage(damage: Int)
}
protocol Shootable {
func shoot(target: Targetable)
}
class Pistol: Shootable {
func shoot(target: Targetable) {
target.takeDamage(damage: 5)
}
}
class Enemy: Targetable {
var health = 100
func takeDamage(damage: Int) {
health = health - damage
print("Current health is: \(health)")
}
}
class Player {
var gun: Shootable
func shoot(target: Targetable) {
gun.shoot(target: target)
}
init(gun: Shootable) {
self.gun = gun
}
}
let player = Player(gun: Pistol())
let enemy = Enemy()
player.shoot(target: enemy)
现在,我想在Targetable
上创建一个协议扩展,当符合Targetable
的任何类都有takeDamage
的默认实现时,会减少health
属性。问题是,因为health
属性是存储值,所以我无法在协议扩展中访问health
。
我试过这样做:
extension Targetable {
func takeDamage(damage: Int, health: Int) {
}
}
但是在通话网站上,将health
传递给函数似乎没有意义。
我该如何实施?谢谢!