如何检查泛型参数关联类型?
How to check generic parameter associated type?
为了弄清楚我在问什么,请考虑以下示例:
protocol Food {}
protocol Meat: Food {}
protocol Animal {
associatedtype Food
func eat(food: Food)
}
protocol Funny {}
struct Cat: Animal {
func eat(food: Meat) {
print("Mewo!")
}
}
我想做的是将其他具有特定条件的动物与 Cat
进行比较;假设我们要声明一个函数,将猫与以下内容进行比较:funny animal(将 T
与约束进行比较:它必须符合拖协议),方法签名将被声明为 -in Cat
structure-:
func compareWithFunnyAnimal<T: Animal & Funny>(animal: T) {}
它工作正常,但是如果我想比较猫和必须吃 Meat
的动物(根据 T
关联类型进行比较,即 Food
)怎么办?我试着做 -in Cat
structure-:
// animal must eat Meat
func compareWithAnimal<T: Animal & T.Food == Meat>(animal: T) {}
但是 - 显然 - 它没有用。
泛型参数关联类型怎么比较呢?是否有一种解决方法需要添加多个通用参数?
您应该使用通用 where
子句来检查 T.Food
是否属于 Meat
.
类型
func compareWithAnimal<T: Animal>(animal: T) where T.Food == Meat {
}
阅读更多关于 Generic where Clause
为了弄清楚我在问什么,请考虑以下示例:
protocol Food {}
protocol Meat: Food {}
protocol Animal {
associatedtype Food
func eat(food: Food)
}
protocol Funny {}
struct Cat: Animal {
func eat(food: Meat) {
print("Mewo!")
}
}
我想做的是将其他具有特定条件的动物与 Cat
进行比较;假设我们要声明一个函数,将猫与以下内容进行比较:funny animal(将 T
与约束进行比较:它必须符合拖协议),方法签名将被声明为 -in Cat
structure-:
func compareWithFunnyAnimal<T: Animal & Funny>(animal: T) {}
它工作正常,但是如果我想比较猫和必须吃 Meat
的动物(根据 T
关联类型进行比较,即 Food
)怎么办?我试着做 -in Cat
structure-:
// animal must eat Meat
func compareWithAnimal<T: Animal & T.Food == Meat>(animal: T) {}
但是 - 显然 - 它没有用。
泛型参数关联类型怎么比较呢?是否有一种解决方法需要添加多个通用参数?
您应该使用通用 where
子句来检查 T.Food
是否属于 Meat
.
func compareWithAnimal<T: Animal>(animal: T) where T.Food == Meat {
}
阅读更多关于 Generic where Clause