2

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?

1 Answer 1

2

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]

Sign up to request clarification or add additional context in comments.

3 Comments

This is a sidenote, but apparently the first element of an array in swift is [1] as opposed to [0]?
swift array indexing is zer0-based also , for your case you can easily test it with shape[2] and it will crash the app with index-out of range exception
OK. That makes more sense.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.