Swift 一致性要求中的类型不指通用参数或关联类型
在Swift 2中,我有以下协议Swift 一致性要求中的类型不指通用参数或关联类型,swift,generics,interface,swift2,Swift,Generics,Interface,Swift2,在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的类型签名更改为,我可以为Fig
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
的类型签名更改为,我可以为Fightable实现协议扩展,以便在符合Stats
的所有值类型之间提供fight
的共享实现
func fight (other: Self) -> Bool
并根据需要实施扩展
extension Fightable where Self : Stats {
func fight (other: Self) -> Bool {
return self.defense > other.attack
}
}
上述实现的问题在于它要求值类型相同(Human
s不能与Goblin
s战斗)。我当前的目标是实现一个协议扩展,它为任何值类型的组合提供默认的fight
,只要它们实现Stats
下面的代码
extension Fightable where Fightable : Stats {
func fight (other: Fightable) -> Bool {
return self.defense > other.attack
}
}
产生错误
一致性要求中的类型“Fightable”不指通用参数或关联类型
如何确保其他可战斗类型也符合此扩展的统计信息
我使用的是Xcode 7 beta 1。一种适合我的方法是在您的Fightable协议中创建一个typealias。因此,您可以在协议扩展中约束fight函数的参数。由于这种情况,您还必须使您的战斗功能具有通用性(可战斗性可不仅仅用作通用约束) 在代码中,它如下所示:
protocol Fightable {
// make typealias
typealias F = Fightable
// make function generic
func fight<F: Fightable>(other: F) -> Bool
}
protocol Stats {
var defense: Int { get }
var attack: Int { get }
}
// constraint F and Self
extension Fightable where F : Stats, Self: Stats {
func fight(other: F) -> Bool {
return self.defense > other.attack
}
}
// example of an implementation
struct Human: Fightable {
func fight<F: Fightable>(other: F) -> Bool {
return true
}
}
protocol-Fightable{
//制作typealias
typealias F=可战斗
//使函数通用
func战斗(其他:F)->Bool
}
协议统计数据{
var防御:Int{get}
var攻击:Int{get}
}
//约束F与自我
扩展可战斗,其中F:Stats,Self:Stats{
func战斗(其他:F)->Bool{
返回自卫>其他攻击
}
}
//实现示例
结构人:可以战斗{
func战斗(其他:F)->Bool{
返回真值
}
}
很抱歉,我误解了你的问题。因此,如果我理解正确(希望如此),就不可能通过协议扩展(至少在这些约束条件下)获得fight
函数的默认实现。因为如果您想要other
符合Fightable
和Stats
的要求,那么other
可以是任何Fightable
的功能就不再是以前的功能了。所以它没有实现所需的功能。
作为解决方法,我建议(使用现有代码):
这对我不起作用,因为你仍然需要为符合Fightable和Stats的结构实现fight函数。
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 }
}
extension Fightable where Self : Stats {
// directly conforming to the protocol
func fight (other: Fightable) -> Bool {
if let otherStat = other as? Stats {
return self.defense > otherStat.attack
}
// providing a good way if other does not conform to Stats
return false
}
}