使用协议扩展更改类中的存储属性

时间:2017-09-01 13:50:30

标签: ios swift protocols

我正在学习面向协议的编程,我有一个敌人和玩家的模型,玩家可以像这样伤害敌人:

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传递给函数似乎没有意义。

我该如何实施?谢谢!

0 个答案:

没有答案