句の一部としてSelf
をプロトコルの一部で使用しようとすると、問題が発生しています。汎用関数でSelfを使用するとエラーが発生する
protocol Animal {
associatedtype FoodSource
func eat(_ food:FoodSource)
}
// The where clause specifies that T2 must conform to
// whatever type is T1's FoodSource associated type
func feed<T1: Animal, T2>(animal:T1, food:T2) where T2 == T1.FoodSource {
animal.eat(food)
}
機能フィードは、最初のパラメータがAnimal
プロトコルに準拠しなければならないことを宣言するために括弧付きステートメントを使用しています。たとえば
は、私はこのプロトコルと定義され、この汎用的な機能を持っていると言います。 where
句を使用して、2番目のパラメータの型が、1番目のパラメータの関連する型に準拠している必要があることを宣言します。
この汎用関数の要件に準拠したクラスを作成することができ、すべてが完全に機能します。例:
protocol Meat {}
protocol Vegetable {}
class Rabbit : Animal {
typealias FoodSource = Vegetable
func eat(_ food:FoodSource) {
print("the Rabbit ate the \(type(of:food))")
}
}
class Lion : Animal {
typealias FoodSource = Meat
func eat(_ food:FoodSource) {
print("the Lion ate the \(type(of:food))")
}
}
class Carrot : Vegetable {}
class Steak : Meat {}
class ChickenSalad : Meat, Vegetable {}
// works because Carrot conforms to Vegetable
// prints: "the Rabbit ate the Carrot"
feed(animal: Rabbit(), food: Carrot())
// works because Steak conforms to Meat
// prints: "the Lion ate the Steak"
feed(animal: Lion(), food: Steak())
// works because ChickenSalad conforms to Meat
// prints: "the Lion ate the ChickenSalad"
feed(animal: Lion(), food: ChickenSalad())
// works because ChickenSalad conforms to Vegetable
// prints: "the Rabbit ate the ChickenSalad"
feed(animal: Rabbit(), food: ChickenSalad())
これまでのところとても良いです。しかし
、私はプロトコルの一部として、ジェネリック医薬品の同じパターンを実装する場合、それはもはや作品:
error: generic parameter 'T' could not be inferred
SteakSalad().feed(to: Lion())
^
は、次のとおりです。
実行protocol Food {
func feed<T:Animal>(to:T) where Self == T.FoodSource
}
extension Food {
func feed<T:Animal>(to animal:T) where Self == T.FoodSource {
animal.eat(self)
}
}
class SteakSalad : Food, Meat, Vegetable {}
SteakSalad().feed(to: Lion())
は、このブロックは、次のエラーがスローされます希望の動作を達成するための何らかの方法がありますか?
https://stackoverflow.com/questions/36810270/swift-protocols-with-associated-type-requirement-and-default-implementation – suhit
私は厚いかもしれませんが、私はこのことが私の場合。私は、提供される例が内容に関して非常に似ていることを知っていますが、それは別の問題のようです。リンクされたポストの場合、型推論は 'Cow'には機能しません。なぜなら' Cow.Food'の関連型はそのメソッドの署名なしでは決めることができないからです。私の例では、型が提供されたパラメータ(この場合は 'Lion')から直接推論されない理由を理解していません。 – sak