【发布时间】:2015-06-16 18:13:57
【问题描述】:
在 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 }
}
如果我将fight 的类型签名更改为
func fight (other: Self) -> Bool
并将扩展实现为
extension Fightable where Self : Stats {
func fight (other: Self) -> Bool {
return self.defense > other.attack
}
}
上述实现的问题在于它要求值类型相同(Humans 无法对抗Goblins)。我目前的目标是实现一个协议扩展,只要它们实现了 Stats,它就为任何值类型组合提供fight 的默认实现。
以下代码
extension Fightable where Fightable : Stats {
func fight (other: Fightable) -> Bool {
return self.defense > other.attack
}
}
产生错误
一致性要求中的“Fightable”类型不引用泛型参数或关联类型
如何确保其他 Fightable 类型也符合此扩展的统计信息?
我正在使用 Xcode 7 beta 1。
【问题讨论】:
标签: swift generics interface swift2