Swift 如何检查泛型参数关联类型? 为了澄清我的要求,请考虑下面的例子: protocol Food {} protocol Meat: Food {} protocol Animal { associatedtype Food func eat(food: Food) } protocol Funny {} struct Cat: Animal { func eat(food: Meat) { print("Mewo!") } }

Swift 如何检查泛型参数关联类型? 为了澄清我的要求,请考虑下面的例子: protocol Food {} protocol Meat: Food {} protocol Animal { associatedtype Food func eat(food: Food) } protocol Funny {} struct Cat: Animal { func eat(food: Meat) { print("Mewo!") } },swift,generics,swift-protocols,Swift,Generics,Swift Protocols,我想做的是将其他具有特定条件的动物与猫进行比较;假设我们想要声明一个函数来比较一只猫和一只有趣的动物(比较T和一个约束:它必须符合两个协议),方法签名将声明为-incatstructure-: func compareWithFunnyAnimal<T: Animal & Funny>(animal: T) {} // animal must eat Meat func compareWithAnimal<T: Animal & T.Food == Meat&

我想做的是将其他具有特定条件的动物与猫进行比较;假设我们想要声明一个函数来比较一只猫和一只有趣的动物(比较
T
和一个约束:它必须符合两个协议),方法签名将声明为-in
cat
structure-:

func compareWithFunnyAnimal<T: Animal & Funny>(animal: T) {}
// animal must eat Meat
func compareWithAnimal<T: Animal & T.Food == Meat>(animal: T) {}
但是,很明显,它不起作用


当涉及到泛型参数关联类型时,如何进行这样的比较?是否有需要添加多个通用参数的解决方法?

您应该使用generic
where
子句检查
T.Food
是否属于
Meat
类型

func compareWithAnimal<T: Animal>(animal: T) where T.Food == Meat {


}
func比较动物(动物:T),其中T.食物==肉{
}

阅读更多关于

没有Xcode的信息,但IBM沙盒接受了这一点:
func compareWithAnimal(动物:t),其中t.Food==肉类