Reputation: 4764
I have an NSArray
consisting of NSArrays
of strings created in Objective-C.
I now want to loop through the items in the array in a swift class and am having trouble with the syntax.
The original Objective-C Array of arrays looks like the following:
NSArray* shapes =@[@[@"square",@"square.png"],@[@"circle",@"circle.png"],@[@"square",@"square.png"]];
I am able to get and print the Array from the Objective-C class using:
let shapes:Array = Utilities.sharedInstance().getShapes
The following to loop through the array, however, is not compiling:
var term : String = ""
var pic : String = ""
for shape in shapes {
term = shape[1] //ERROR HERE
pic = shape[2] //SAME ERROR HERE
}
It gives the error: Type 'Any' has no subscript members
What is the proper syntax to loop through the elements?
Upvotes: 2
Views: 176
Reputation: 100533
You can try
let shapes = Utilities.sharedInstance().getShapes as! [[String]]
Your Array
elements are of type Any
so you can't use [] with them until you cast , it's always the case when you use bridged code from objective-c , so you have to be specific about the actual type you use , also i encourage
struct Item {
let term,pic:String
}
Then
let res:[Item] = shapes.map { Item(term:$0[0],pic:$0[1]) }
an irrelevant note but important you can do
NSArray* shapes = @[@"square",@"circle",@"square"];
then the matter of appending .png is simple instead of having an [[String]]
directly it's [String]
Upvotes: 2