Swift为什么不能自动将泛型类型参数转换为其超类? [英] Why can't Swift automatically convert a generic type parameter to its superclass?

查看:44
本文介绍了Swift为什么不能自动将泛型类型参数转换为其超类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Swift中考虑以下内容:

Consider the following in Swift:

struct GenericStruct<T> {}
class A {}
class B: A {}

func doSomething() -> GenericStruct<A> {
   return GenericStruct<B>()
}

这给出了错误:

无法将类型为 GenericStruct< B> 的返回表达式转换为类型为 GenericStruct< A>

Cannot convert return expression of type GenericStruct<B> to return type GenericStruct<A>

但是 B A 的子类.

  • 为什么Swift无法将 GenericStruct< B> 转换为 GenericStruct< A> ?
  • 在这种情况下应该做什么?

推荐答案

Swift泛型是不变的,这意味着即使两个泛型类型参数具有继承关系,它们也不相关.不变的泛型类型不能互相强制转换,因为它们之间没有继承关系.

Swift generics are invariant, meaning that two generic types are unrelated even if their generic type parameters have an inheritance relation. Invariant generic types cannot be cast to each other since they have no inheritance relation to each other.

这意味着 GenericStruct< B> GenericStruct< A> 完全不相关,即使 B A的子类也是如此,因此您不能将其中一个投向另一个.

This means that GenericStruct<B> and GenericStruct<A> are completely unrelated even if B is a subclass of A, hence you cannot cast one to the other.

这篇关于Swift为什么不能自动将泛型类型参数转换为其超类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆