我在嘗試將Self
作爲協議一部分的泛型函數中的where
子句的一部分時遇到問題。在泛型函數中使用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
子句聲明第二個參數的類型必須符合第一個參數的關聯類型。
有可能創建符合這個通用函數的要求的類,並且一切都很完美。例如:
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())
到目前爲止這麼好。
然而,當我實現仿製藥相同的模式作爲協議的一部分,它不再起作用:
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())
執行時,該塊將引發以下錯誤:
error: generic parameter 'T' could not be inferred
SteakSalad().feed(to: Lion())
^
是有一些方法可以達到理想的行爲?
https://stackoverflow.com/questions/36810270/swift-protocols-with-associated-type-requirement-and-default-implementation – suhit
也許我很厚,但我不確定這究竟是如何適用於我案件。我知道所提供的例子在內容方面非常相似,但它似乎是一個單獨的問題。在鏈接帖子的情況下,類型推斷不再適用於'Cow',因爲如果沒有該方法簽名,就不能確定Cow.Food的關聯類型。在我的例子中,我不明白爲什麼不直接從提供的參數(在這種情況下是'Lion')推斷出類型。 – sak