Swift cannot specialize generic parameter when the specializing type is constrained with additional protocol

Viewed 45

Imagine the following scenario:

class Food {}

protocol Growable {}

class Animal<T: Food> {}

let animal1 = Animal<Food>() // Ok
let animal2 = Animal<Food & Growable>() // Compile error: 'Animal' requires that 'Food & Growable' inherit from 'Food'

Clearly, if we have a variable of type Food & Growable, this variable is also of type Food. Yet the generic Parameter T of the Animal class can't be specialized with the type Food & Growable. Why is that?

1 Answers

The error message is a bit strange but what you are trying to do is invalid.

You cannot create generics using protocols. When creating a generic, you have to use a concrete type. Not a protocol.

Food & Growable is not a concrete type.

You would need a subclass:

class GrowableFood: Food, Growable {
   ...
}

let animal2 = Animal<GrowableFood>()

or, you can extend Animal if Food is Growable:

extension Animal where T: Growable {
}
Related