2
我不确定where
子句可以将通用参数限制为从某个协议继承的协议。限制从协议继承的协议泛型参数
protocol Edible {}
protocol PetFood: Edible {}
struct CatFood: PetFood {}
struct Rocks {}
func eat<T: Edible>(_ item: T) -> String {
return "Just ate some \(type(of: item))"
}
let food: CatFood = CatFood()
eat(food) //"Just ate some CatFood"
let moreFood: PetFood = CatFood()
//eat(moreFood) //Cannot invoke 'eat' with an argument list of type '(PetFood)'
func eatAnything<T>(_ item: T) -> String {
return "Just ate some \(type(of: item))"
}
eatAnything(moreFood) //This works, obviously
eatAnything(Rocks()) //But, of course, so does this...
有什么办法来限制eatAnything()
允许协议类型,但只有那些从Edible
继承?
嗯,肯定的 - 它只是一个简单的例子来说明这个问题。 – andyvn22
@ andyvn22我更新了我的答案 –