I simplify my trouble into a small demo about using Generic Type and protocol.here is the code.
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)'
}
the problem is I am sure that in for-loop item get right Food, but the compiler give me that error