快速遍历多维数组

问题描述 投票:3回答:2

因此,我尝试遍历NSArray。我的NSArray是一个字符串数组的数组。这是前1.5个元素的复制粘贴]

(
    (
    "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",

这是让我头疼的功能

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

        }
    }
}

'cellDescripters'是一个全局变量,它是我在顶部概述的数组,基本上是一个字符串数组的数组。

当我打印'item'的类型时,根据我的理解,它是__NSArrayM类型的,它是一个NSMutableArray。查看文档NSMutableArrays是可迭代的。

但是当我去编译这段代码时,我得到了错误:

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

任何帮助将不胜感激。

swift optional
2个回答
4
投票

我认为以下示例可为您提供帮助例如我有像你这样的字符串数组=

[[“饮料”,“食品”,“供应商”],[“其他原料”,“药物”]];]

  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)")
            }
       }

输出

index : 0 item: beverages
index : 0 item: food
index : 0 item: suppliers
index : 1 item: other stuff
index : 1 item: medicine

0
投票

这是在Swift中迭代2D数组的更通用的解决方案。已在iOS 13的Swift 4中测试。仅适用于Swift数组,请参见以下链接将NSArray转换为数组: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
        })
    }

}

示例用法:

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

for element in sampleMatrix.matrixIterator() {
    print(element)
}
© www.soinside.com 2019 - 2024. All rights reserved.