Reputation: 540
Say I have two arrays:
var exterior: Array<(name: String, value: (code: Code, pass: Bool))> = []
var interior: Array<(name: String, value: (code: Code, type: Type, pass: Bool))> = []
I have a UISegmentedControl that, depending on which segment is selected, will show data from the respective array. To reduce boilerplate, I'd like to use one fuction for setup:
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...
}
}
}
}
This won't work since I cannot cast to an array that holds Any
. If I change the type of both interior
and exterior
to Any
and try casing them to their respective types, I get an error: can't unsafeBitCast between types of different sizes
. What are my options in this situation?
Upvotes: 0
Views: 416
Reputation: 4757
You cannot cast Array<Any>
to Array<AnyOther>
, because there is no inheritance between Array<Any>
and Array<AnyOther>
. You should actually convert such arrays like so:
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]
Upvotes: 3