假设我想在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
}
}
1条答案
按热度按时间of1yzvn41#
您需要添加常规约束。