简体   繁体   English

迅速-具有继承的泛型类

[英]swift - Generic classes with inheritance

When I try to execute the code below, I get the following error 当我尝试执行以下代码时,出现以下错误

error: cannot convert value of type 'X' to specified type 'X' 错误:无法将类型“ X”的值转换为指定的类型“ 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

In Swift, generics are invariant , eg any X<A> will never be assignable to X<B> , regardless of the inheritence relationship between A and B . 在夫特,泛型是不变的 ,例如任何X<A>永远不会分配给X<B>而不管之间的传承关系的AB

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

These will compile (since Swift 3) - but these a special cases treated by some hard-coded rules of the the compiler. 它们将进行编译(自Swift 3起)-但是这些特殊情况由编译器的一些硬编码规则处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM