我试图将一个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? }
答案 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)