为什么可以';我不能在Swift中向一个超类投射一系列选项吗?

为什么可以';我不能在Swift中向一个超类投射一系列选项吗?,swift,generics,Swift,Generics,我试图将派生?数组强制转换为基?数组,但我的强制转换无法编译: 1> class Base { } 2> class Derived: Base { } 3> let x: [Derived?] = [Derived(), Derived()] x: [Derived?] = 2 values { [0] = 0x0000000100f04970 { __lldb_expr_1.Base = {...} } [1] = 0x0000000

我试图将
派生?
数组强制转换为
基?
数组,但我的强制转换无法编译:

  1> class Base { }  
  2> class Derived: Base { } 
  3> let x: [Derived?] = [Derived(), Derived()] 
x: [Derived?] = 2 values {
  [0] = 0x0000000100f04970 {
    __lldb_expr_1.Base = {...}
  }
  [1] = 0x0000000100f07580 {
    __lldb_expr_1.Base = {...}
  }
}
  4> let y: [Base?] = x 
repl.swift:4:18: error: cannot convert value of type '[Derived?]' to specified type '[Base?]'
let y: [Base?] = x
                 ^
为什么不编译,我如何才能实现这个结果

我有这个解决办法,但似乎有点笨拙:

let y: [Base?] = x.map { $0 as Base? }

通过创建一个似乎要执行类型转换的函数,可以使语法不那么混乱:

class Base {} 
class Derived: Base {}

func OptionalArray<T, U>(array:[T?]) -> [U?]
{ return array.map({ $0 as! U? }) } 

let x: [Derived?] = [Derived(), Derived()] 
var y: [Base?]    = OptionalArray(x)
类基类{}
派生类:基{}
func OptionalArray(数组:[T?])->[U?]
{return array.map({$0 as!U?})}
设x:[派生?]=[派生(),派生()]
变量y:[基?]=可选数组(x)

您可以通过创建一个看起来可以执行类型转换的函数来减少语法的混乱:

class Base {} 
class Derived: Base {}

func OptionalArray<T, U>(array:[T?]) -> [U?]
{ return array.map({ $0 as! U? }) } 

let x: [Derived?] = [Derived(), Derived()] 
var y: [Base?]    = OptionalArray(x)
类基类{}
派生类:基{}
func OptionalArray(数组:[T?])->[U?]
{return array.map({$0 as!U?})}
设x:[派生?]=[派生(),派生()]
变量y:[基?]=可选数组(x)

正如您的解决方案所示:Swift不会推断出一个包含
派生
类型元素的数组可直接分配给
类型的数组:您需要在元素级别进行类型转换。我认为
.map
解决方案一点也不麻烦。这里有类似的问题:。正如您的解决方案所示:Swift不会推断一个数组,其中包含
派生
类型的元素,可以直接分配给
类型的数组:您需要在元素级别上进行类型转换。我认为
.map
解决方案一点也不麻烦。这里有类似的问题:。