tonytran tonytran - 1 year ago 72
Swift Question

why I am getting "generic parameter could not be inferred" , generic type

I'm learning generic type + protocol by creating some foods which conform a protocol named


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

Next, I am creating a struct
which has one method using a generic type:

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

When I'm doing like following:

let array: [Nutrition] = [Individual(fName: "A", lName: "AAA").eat(Hamburger),Individual(fName: "B", lName: "BBB").eat(PadThai)]

the compiler keeps complaining:

Generic parameter 'T' could not be inferred

I'm also looking at other posts regarding to this error but still can not find a solution. Does anyone know how to fix this.

Answer Source

Your array expects instances rather than the type themselves:

let array: [Nutrition] = [
    Individual(fName: "A", lName: "AAA").eat(Hamburger()),
    Individual(fName: "B", lName: "BBB").eat(PadThai())