面向协议的编程Swift -可识别

uemypmqf  于 2022-12-02  发布在  Swift
关注(0)|答案(1)|浏览(134)

假设我想在swift中用面向协议的编程来建模一个幻想游戏。下面的代码会产生以下错误:
协议“Character”只能用作泛型约束,因为它具有Self或关联的类型要求
这有什么问题,怎么做才对?

protocol Character: Identifiable {
    var name: String {get}
    var maxHealt: Int {get}
    var healt: Int { get set }
}
extension Character {
    var id: String {return name}
    mutating func setHealth(newValue: Int) {
        healt = newValue
    }
}

protocol Fighter {
    var attackPower: Int { get }
}
extension Fighter {
    func attack(enemy: Character ) -> Character {
        var enemy = enemy
        enemy.setHealth(newValue: enemy.maxHealt - self.attackPower)
        return enemy
    }
}
of1yzvn4

of1yzvn41#

您需要添加常规约束。

extension Fighter {
    func attack<T: Character>(enemy: T ) -> T { //<-- Here
        var enemy = enemy
        enemy.setHealth(newValue: enemy.maxHealt - self.attackPower)
        return enemy
    }
}

相关问题