为什么我不能在Swift中向超类投射一系列选项?

时间:2016-01-31 14:03:17

标签: swift generics

我试图将一个Derived?数组投射到一个Base?数组中,但是我的演员没有编译:

  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
                 ^

为什么不编译,我怎样才能实现这个结果?

我有这个解决方法,但它似乎有点kludgy:

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

1 个答案:

答案 0 :(得分:0)

通过创建一个似乎可以进行类型转换的函数,你可以使语法少一点kludgy:

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)