Home > Enterprise >  How to get the row and column index in ForEach loop of a 2D array in swiftUI?
How to get the row and column index in ForEach loop of a 2D array in swiftUI?

Time:09-12

I would like to get the row and column index in ForEach loop of a 2D array in swiftUI.

let array = [
    
    ["1", "2", "3"],
    ["4", "5", "6"],
    ["7", "8", "9"]
    
]

ForEach(array, id: .self) { row in

    ForEach(row, id: \.self) { element in

// How to get the index i and j for row and column of a 2D array in swiftUI ???

    }

}

CodePudding user response:

Since you have an array of [String] you must have 2 ForEach:

ForEach(Array(row.enumerated()), id:\.self) { i, array in
    ForEach(Array(array.enumerated()), id: \.self) { j, element in
        //do something
    }
}

CodePudding user response:

try something like this, ...to get the index i and j for row and column of a 2D array...:

struct ContentView: View {
    let array = [["1", "2", "3"],["4", "5", "6"],["7", "8", "9"]]
    
    var body: some View {
        ForEach(array.indices, id: \.self) { i in
            ForEach(array[i].indices, id: \.self) { j in
                Text(array[i][j])
            }
        }
    }
}
  • Related