swift - 在 Swift 中将数组转换为特定类型

标签 swift

假设我有两个数组:

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 并尝试将它们设置为各自的类型,我会收到错误消息:不能在不同大小的类型之间使用 unsafeBitCast。在这种情况下我有什么选择?

最佳答案

你不能投Array<Any>Array<AnyOther> , 因为 Array<Any> 之间没有继承关系和 Array<AnyOther> .实际上,您应该像这样转换这样的数组:

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]

关于swift - 在 Swift 中将数组转换为特定类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37008068/

相关文章:

ios - 推送 UIView 时隐藏 UITabBar

swift - 如何在 Linux 上快速线程 sleep

ios - Storyboard内容在一段时间后隐藏 - iOS,swift

ios - 无法创建程序化广播组

ios - Swift - 来自结构数组的数据未显示在 TableView 中

swift - `swift test` 产生 "symbol(s) not found for architecture x86_64"链接器错误

swift - 如何在 perform(selector, withObject) 中将闭包作为参数传递

ios - 线程 1 : Fatal error: NSArray element failed to match the Swift Array Element type

ios - 为什么标签栏消失了?

ios - 无法从第二个数据源动态添加自定义单元格