5

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.

3
  • 1
    Why are you using NSArray in Swift? Commented Feb 7, 2018 at 4:30
  • Well I am reading data from a plist file into that array. Why NSArray? I'm not entirely sure, I was following a tutorial. How else could I read in data from a plist file? Commented Feb 7, 2018 at 4:32
  • 1
    change cellDescripters type to [[String]] instead of NSMutableArray. Commented Feb 7, 2018 at 4:56

2 Answers 2

8

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
Sign up to request clarification or add additional context in comments.

1 Comment

sorry i cant understand, you mean to say you have to prepare dictionary like ["0":[beverages","xyx","abc"], "1":[other stuff","medecine"]] right
1

Here's a more generic solution for iterating 2D arrays in Swift. Tested in Swift 4 on iOS 13. Works only on Swift arrays, see the following link for converting your NSArray to Arrays: https://stackoverflow.com/a/40646875/1960938

// 2D array extension explanation: https://stackoverflow.com/a/44201792/1960938
fileprivate extension Array where Element : Collection, Element.Index == Int {

    typealias InnerCollection = Element
    typealias InnerElement = InnerCollection.Iterator.Element

    func matrixIterator() -> AnyIterator<InnerElement> {
        var outerIndex = self.startIndex
        var innerIndex: Int?

        return AnyIterator({
            guard !self.isEmpty else { return nil }

            var innerArray = self[outerIndex]
            if !innerArray.isEmpty && innerIndex == nil {
                innerIndex = innerArray.startIndex
            }

            // This loop makes sure to skip empty internal arrays
            while innerArray.isEmpty || (innerIndex != nil && innerIndex! == innerArray.endIndex) {
                outerIndex = self.index(after: outerIndex)
                if outerIndex == self.endIndex { return nil }
                innerArray = self[outerIndex]
                innerIndex = innerArray.startIndex
            }

            let result = self[outerIndex][innerIndex!]
            innerIndex = innerArray.index(after: innerIndex!)

            return result
        })
    }

}

An example usage:

let sampleMatrix = [
    ["a", "b", "c"],
    ["d", "e"],
    [],
    ["f"],
    []
]

// Should print: a, b, c, d, e, f      
for element in sampleMatrix.matrixIterator() {
    print(element)
}

Comments

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.