[英]Swift cannot specialize generic parameter when the specializing type is constrained with additional protocol
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
.显然,如果我们有一个
Food & Growable
类型的变量,这个变量也是Food
类型的。 Yet the generic Parameter T
of the Animal
class can't be specialized with the type Food & Growable
.然而,
Animal
类的通用参数T
不能特化为Food & Growable
类型。 Why is that?这是为什么?
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 . Food & Growable
不是一个具体的类型。
You would need a subclass:你需要一个子类:
class GrowableFood: Food, Growable {
...
}
let animal2 = Animal<GrowableFood>()
or, you can extend Animal
if Food
is Growable
:或者,如果
Food
is Growable
,您可以扩展Animal
:
extension Animal where T: Growable {
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.