swift - 如何检查泛型参数关联类型?

标签 swift generics swift-protocols

为了阐明我在问什么,请考虑以下示例:

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 与约束进行比较:它必须符合两个协议(protocol)), 方法签名将声明为 -in Cat structure-:

func compareWithFunnyAnimal<T: Animal & Funny>(animal: T) {}

它工作正常,但是如果我想比较猫和必须吃 Meat 的动物(基于 T 关联类型进行比较,即 食物) ?我试着在 Cat 结构中做 -:

// 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 的信息

关于swift - 如何检查泛型参数关联类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48888339/

相关文章:

swift - 无法转换具有匹配类型的类型的值 - 我遇到了编译器限制吗?

swift - 如何从通用函数返回值作为协议(protocol)的实现?

ios - 仅将 4 行代码从 objective-c 转换为 swift(指针)

使用 Kotlin 中的 Guava 的 toImmutableSortedMap 收集器时出现泛型错误

Swift switch 语句考虑了 Int 的所有情况,但编译器仍然显示错误

generics - 如何在堆上构造动态大小的对象

ios - 具有数字和可比较协议(protocol)的 Swift 泛型类

swift - 如何解决 Swift 协议(protocol)的规范问题

ios - CAGradientLayer 位置不正确

swift - iOS10 中的 PFImageView loadInBackground() 问题