我正在通过创建一些符合名为Nutrition
protocol Nutrition {
var calories: Double { get set }
var price: Double { get set }
}
struct Hamburger: Nutrition {
var calories = 100.0
var price = 8.0
}
struct PadThai: Nutrition {
var calories = 110.0
var price = 8.50
}
接下来,我正在创建一个结构Individual
,它有一个使用泛型类型的方法:
struct Individual {
var firstName: String
var lastName: String
init(fName: String, lName: String)
{
firstName = fName
lastName = lName
}
func eat<T: Nutrition>(food: T) -> T {
return food
}
当我这样做时:
let array: [Nutrition] = [Individual(fName: "A", lName: "AAA").eat(Hamburger),Individual(fName: "B", lName: "BBB").eat(PadThai)]
编译器一直在抱怨:
Generic parameter 'T' could not be inferred
我也在查看有关此错误的其他帖子,但仍无法找到解决方案。有谁知道如何解决这个问题。
答案 0 :(得分:2)
您的数组需要实例而不是类型本身:
let array: [Nutrition] = [
Individual(fName: "A", lName: "AAA").eat(Hamburger()),
Individual(fName: "B", lName: "BBB").eat(PadThai())
]