在 Swift 2 中,我有以下协议
protocol Fightable {
// return true if still alive, false if died during fight
func fight (other: Fightable) -> Bool
}
protocol Stats {
var defense: Int { get }
var attack: Int { get }
}
我可以为 Fightable 实现一个协议扩展,以提供fight
跨所有值类型的共享实现,Stats
如果我将类型签名更改fight
为
func fight (other: Self) -> Bool
并将扩展实现为
extension Fightable where Self : Stats {
func fight (other: Self) -> Bool {
return self.defense > other.attack
}
}
上述实现的问题在于它要求值类型相同(Human
s can't fight Goblin
s)。我目前的目标是实现一个协议扩展,fight
只要它们实现了 Stats,就可以为任何值类型组合提供默认实现。
以下代码
extension Fightable where Fightable : Stats {
func fight (other: Fightable) -> Bool {
return self.defense > other.attack
}
}
产生错误
一致性要求中的“可战斗”类型不引用泛型参数或关联类型
如何确保其他 Fightable 类型也符合此扩展的统计信息?
我正在使用 Xcode 7 beta 1。