【发布时间】:2018-02-25 21:10:14
【问题描述】:
我不确定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 继承的协议类型?
【问题讨论】:
标签: swift generics inheritance protocols