【问题标题】:Why can't I cast an array of optionals to a superclass in Swift?为什么我不能在 Swift 中将一组可选项转换为超类?
【发布时间】: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 的解决方法一点也不笨拙。

标签: swift generics


【解决方案1】:

您可以通过创建一个看起来会进行类型转换的函数来使语法不那么繁琐:

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)

【讨论】:

    猜你喜欢
    • 2021-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-31
    • 1970-01-01
    相关资源
    最近更新 更多