迅捷-具有继承的泛型类 [英] swift - Generic classes with inheritance
问题描述
当我尝试执行以下代码时,出现以下错误
When I try to execute the code below, I get the following error
错误:无法将类型"X"的值转换为指定的类型 'X'
error: cannot convert value of type 'X' to specified type 'X'
不迅速支持泛型继承吗?有解决方法吗?
Doesn't swift support inheritance with generics? Is there a workaround for this?
class Parent{ }
class Child:Parent{ }
class X<T>{
var name: String?
}
var test:X<Parent> = X<Child>() //Compiler Error
推荐答案
在Swift中,泛型是不变,例如无论A
和B
之间的继承关系如何,任何X<A>
都不会分配给X<B>
.
In Swift, generics are invariant, e.g. any X<A>
will never be assignable to X<B>
, regardless of the inheritence relationship between A
and B
.
尽管如此,该规则还是有一些例外,涉及数组和可选项(以及其他一些类型):
Nevertheless, there are some exceptions to this rule, regarding Arrays and Optionals (and mabye some other types):
var array2:[Parent] = [Child]()
// same as:
var array1:Array<Parent> = Array<Child>()
var opt1:Parent? = Child()
// same as:
var opt2:Optional<Parent> = Optional<Child>(Child())
这些将编译(自Swift 3起)-但是这些特殊情况由编译器的一些硬编码规则处理.
These will compile (since Swift 3) - but these a special cases treated by some hard-coded rules of the the compiler.
这篇关于迅捷-具有继承的泛型类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!