![](/img/trans.png)
[英]How to pass protocol with associated type (generic protocol) as parameter in Swift?
[英]How to check generic parameter associated type?
為了闡明我的要求,請考慮以下示例:
protocol Food {}
protocol Meat: Food {}
protocol Animal {
associatedtype Food
func eat(food: Food)
}
protocol Funny {}
struct Cat: Animal {
func eat(food: Meat) {
print("Mewo!")
}
}
我想做的是將具有特定條件的其他動物與Cat
進行比較; 比方說,我們要聲明一個貓比較函數: 有趣的 動物 (比較T
了約束:它必須符合拖協議),該方法簽名將被宣布為-in Cat
構築物:
func compareWithFunnyAnimal<T: Animal & Funny>(animal: T) {}
效果很好,但是如果我想將貓與必須Meat
的動物(基於T
關聯類型,即Food
)進行比較該怎么辦? 我嘗試在Cat
結構中執行以下操作:
// animal must eat Meat
func compareWithAnimal<T: Animal & T.Food == Meat>(animal: T) {}
但是-顯然-它沒有用。
關於泛型參數關聯類型,我該如何進行比較? 有一種解決方法需要添加多個通用參數嗎?
您應該使用泛型where
子句檢查T.Food
是否為Meat
類型。
func compareWithAnimal<T: Animal>(animal: T) where T.Food == Meat {
}
閱讀有關Generic where子句的更多信息
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.