【问题标题】:Casting arrays to specific types in Swift将数组转换为 Swift 中的特定类型
【发布时间】:2016-05-03 15:18:51
【问题描述】:

假设我有两个数组:

var exterior: Array<(name: String, value: (code: Code, pass: Bool))> = []
var interior: Array<(name: String, value: (code: Code, type: Type, pass: Bool))> = []

我有一个 UISegmentedControl,根据选择的段,它将显示来自相应数组的数据。为了减少样板,我想使用一个函数进行设置:

func build(section: Section) {
    var data: Array<Any>

    switch section {
    case .Exterior:
        data = exterior
    case .Interior:
        data = interior
    }

    for i in 0...data.count - 1 where i % 4 == 0 {
        for y in i...i + 4 {
            guard y < data.count - 1 else {
                break
            }
            switch section {
            case .Exterior:
                let v = data as! Array<(String, (Report.Code, Bool))>
                // Do stuff here...
            case .Interior:
                let v = data as! Array<(String, (Report.Code, Report.Type, Bool))>
                // Do stuff here...
            }
        }
    }
}

这行不通,因为我无法转换为包含 Any 的数组。如果我将 interiorexterior 的类型都更改为 Any 并尝试将它们封装为各自的类型,我会收到错误:can't unsafeBitCast between types of different sizes。在这种情况下我有什么选择?

【问题讨论】:

  • 既然两种数组类型的区别只是type参数,那么将类型参数声明为可选不是更高效吗?好处是您对两个数组都有一种通用类型,并且您可以通过nil 类型识别exterior。在 Swift 中使用Any 总是最糟糕、最糟糕的习惯,如果可以使用更具体的类型(至少AnyObject)。

标签: swift


【解决方案1】:

您不能将Array&lt;Any&gt; 转换为Array&lt;AnyOther&gt;,因为Array&lt;Any&gt;Array&lt;AnyOther&gt; 之间没有继承关系。您实际上应该像这样转换这样的数组:

let xs: [Any] = [1, 2, 3, 4, 5]
let ys: [Int] = xs.flatMap { $0 as? Int }
print(ys.dynamicType) // Array<Int>
print(ys) // [1, 2, 3, 4, 5]

【讨论】:

    猜你喜欢
    • 2014-11-08
    • 2017-06-10
    • 2016-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-02
    • 1970-01-01
    • 2014-11-12
    相关资源
    最近更新 更多