Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through a multidimensional array in swift

So I am trying to iterate over an NSArray. My NSArray is an array of an array of strings. Here is a copy-paste of the first 1.5 elements

(
    (
    "Tater Tot Nachos",
    "Fried Feta",
    "The Ultimate Feta Bread",
    "Cheese Bread",
    "Aubrees Bread",
    "The Wings!",
    "Coconut Grove Chicken Sicks",
    "Far East Wings",
    "Bacon Brussels Sprouts"
),
    (
    "Shaved Brussels Sprout Salad",
    "Greek Salad",
    "Coronado Cobb Salad",
    "Harvest Salad",

This is the function that's giving me the headache

 func createMenu() {
    if let list = cellDescripters {
        for(index, item) in list.enumerated() {
            for food in item {
                //DO SOMETHING WITH "FOOD"
            }

        }
    }
}

' cellDescripters ' Is a global variable and it is the array I was outlining at the top, basically an array of arrays of strings.

When I print the type of ' item ' I see it's of type __NSArrayM which is an NSMutableArray from my understanding. Looking at documentation NSMutableArrays are iterable.

However when I go to compile this code I get the error:

Type 'Any' does not conform to protocol 'Sequence'

Any help would be greatly appreciated.

like image 401
Nate Schreiner Avatar asked Feb 07 '18 04:02

Nate Schreiner


People also ask

How do you create a multidimensional array in Swift?

In Swift, creating a multi-dimensional array is just a matter of adding another set of brackets. For example, to turn our [String] array into an array of arrays, you would just write [[String]] .

Can we use for each loop for multidimensional array in Java?

Since 2D arrays are really arrays of arrays you can also use a nested enhanced for-each loop to loop through all elements in an array.

How do you declare a multidimensional array?

A multi-dimensional array can be termed as an array of arrays that stores homogeneous data in tabular form. Data in multidimensional arrays are stored in row-major order. The general form of declaring N-dimensional arrays is: data_type array_name[size1][size2]....


1 Answers

I think following example give you help for example i have array of string array like you =

[["beverages", "food", "suppliers"],["other stuff", "medicine"]];

  var arrayExample = [["beverages", "food", "suppliers"],["other stuff", "medicine"]];
//Iterate array through for loop 
       for(index, item) in arrayExample.enumerated() 
         {
            for food in item 
             {
                print("index : \(index) item: \(food)")
            }
       }

OUTPUT

index : 0 item: beverages
index : 0 item: food
index : 0 item: suppliers
index : 1 item: other stuff
index : 1 item: medicine
like image 114
Jaydeep Vyas Avatar answered Oct 21 '22 00:10

Jaydeep Vyas