假设我有两个数组:
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
的数组。如果我将 interior
和 exterior
的类型都更改为 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/