【发布时间】:2016-01-31 14:03:16
【问题描述】:
我正在尝试将 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
^
为什么不编译,我怎样才能达到这个结果?
我有这个解决方法,但看起来有点笨拙:
let y: [Base?] = x.map { $0 as Base? }
【问题讨论】:
-
正如您的解决方法所示:Swift 不会将具有
Derived类型元素的数组作为 assignable 直接推断为Base的数组:您需要这样做元素级别的类型转换。我认为.map的解决方法一点也不笨拙。