私はGeneric Typeとプロトコルを使用する小さなデモを簡単にしています。Swiftプロトコルで使用されている一般的なタイプは動作していません
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ループの項目で右食品を得ることを確信しているが、コンパイラがそのエラーに私
私は、これはXYの問題であることを疑います。これはジェネリックを使用するためのユースケースではないようです(ポリモーフィズムはおそらくもっと意味があります)。しかし、私がその決定を下す前に解決しようとしている実際の問題を理解しなければならないでしょう – Alexander
なぜmanyPeopleの配列ですか? [EatProtocol]はEatProtocol型で、Person型ではありませんか?なぜ男性と女性の両方がケーキと肉を食べることができないのですか? –
@BrianOgden manyPeople配列型[EatProtocol]は[Person]と同じです。この問題では、1つの種類の人が1つの食べ物を食べることができるので、これがエラーの原因です。 – huangxinyu