tonytran
tonytran

Reputation: 1078

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 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
    }

Next, I am creating a struct Individual 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.

Upvotes: 0

Views: 877

Answers (1)

Yasir
Yasir

Reputation: 2372

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())
]

Upvotes: 2

Related Questions