面向协议的编程 Swift - 可识别
Protocol oriented Programming Swift - Identifiable
假设我想在 swift 中使用面向协议的编程来模拟幻想游戏。
下面的代码产生以下错误:
Protocol 'Character' can only be used as a generic constraint because
it has Self or associated type requirements
这里有什么问题?怎么做才对?
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
}
}
您需要添加通用约束。
extension Fighter {
func attack<T: Character>(enemy: T ) -> T { //<-- Here
var enemy = enemy
enemy.setHealth(newValue: enemy.maxHealt - self.attackPower)
return enemy
}
}
假设我想在 swift 中使用面向协议的编程来模拟幻想游戏。 下面的代码产生以下错误:
Protocol 'Character' can only be used as a generic constraint because it has Self or associated type requirements
这里有什么问题?怎么做才对?
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
}
}
您需要添加通用约束。
extension Fighter {
func attack<T: Character>(enemy: T ) -> T { //<-- Here
var enemy = enemy
enemy.setHealth(newValue: enemy.maxHealt - self.attackPower)
return enemy
}
}