【发布时间】:2017-05-24 02:32:27
【问题描述】:
我将我的麻烦简化为一个关于使用通用类型和协议的小演示。这里是代码。
protocol Food {
}
class Meat: Food {
}
class Cake: Food {
}
protocol EatProtocol {
func eat<T: Food>(_: T)
}
class Person: EatProtocol {
func eat<T>(_: T) where T : Food {
print("eat food")
}
}
class Man: Person {
override func eat<T>(_: T) where T : Meat {
print("eat meat")
}
}
class Woman: Person {
override func eat<T>(_: T) where T : Cake {
print("eat cake")
}
}
let man = Man()
let woman = Woman()
let manyPeople: [EatProtocol] = [man, woman]
let meat = Meat()
let cake = Cake()
let manyFood: [Food] = [meat, cake]
for (index, people) in manyPeople.enumerated() {
let food = manyFood[index]
people.eat(food)//error: Cannot invoke 'eat' with an argument list of type '(Food)'
}
问题是我确信在 for-loop 项目中得到正确的食物,但编译器给了我这个错误
【问题讨论】:
-
我怀疑这是一个 XY 问题。这似乎根本不是使用泛型的用例(多态性可能更有意义),但我必须先了解您要解决的真正问题,然后才能做出决定
-
为什么数组 manyPeople: [EatProtocol] 是 EatProtocol 类型而不是 Person 类型?为什么男人和女人不能同时吃饼和肉?
-
@BrianOgden manyPeople 数组类型 [EatProtocol] 与 [Person] 相同。在这个问题中,一种人只能吃一种食物,这就是错误发生的原因。
标签: swift generics inheritance protocols