Ahmad F
Ahmad F

Reputation: 31645

How to check generic parameter associated type?

For the purpose of clarifying what am I asking about, please consider the following example:

protocol Food {}
protocol Meat: Food {}

protocol Animal {
    associatedtype Food
    func eat(food: Food)
}

protocol Funny {}

struct Cat: Animal {
    func eat(food: Meat) {
        print("Mewo!")
    }
}

What I am trying to do is to compare other animals that have specific conditions with Cat; Let's say we want to declare a function that compares a cat with: funny animal (comparing T with a constraint: it must conforms to tow protocols), the method signature would be declared as -in Cat structure-:

func compareWithFunnyAnimal<T: Animal & Funny>(animal: T) {}

It works fine, but what if I want to compare a cat with an animal that must eat Meat (comparing based on T associated type, which is Food) ? I tried to do -in Cat structure-:

// animal must eat Meat
func compareWithAnimal<T: Animal & T.Food == Meat>(animal: T) {}

but -obviously- it did not work.

How can I do such a comparison when it comes to the generic parameter associated type? Is there a workaround that requires to add more than one generic parameter?

Upvotes: 1

Views: 681

Answers (1)

Sandeep
Sandeep

Reputation: 21144

You should rather use generic where clause to check if T.Food is of type Meat.

func compareWithAnimal<T: Animal>(animal: T) where T.Food == Meat {


}

Read more about Generic where Clause

Upvotes: 2

Related Questions