thekodols
thekodols

Reputation: 475

How to display a multi-dimensional array?

I have a 2d array with custom types.

I'd like to do something like:

HStack {
    ForEach(2dArray) { x in
        VStack {
            ForEach(self.2dArray[x.index]) { y in

The main issue I have is that I can't figure out how to get x.index.

Upvotes: 2

Views: 4664

Answers (4)

Objective C
Objective C

Reputation: 41

var data = [[1,2,3],[4,5,6],[7,8,9]]

struct ContentView : View {
  var body: some View {
    VStack {
      ForEach(data, id: \.self) { array in
        HStack{
          ForEach(array, id: \.self) { element in
            Text("\(element)")
          }
        }
      }
    }
  }
}

Upvotes: 2

YoYoHu
YoYoHu

Reputation: 92

struct ContentView : View {
  var body: some View {
    VStack {
      ForEach(data.identified(by: \.self)) { array in
        HStack{
          ForEach(array.identified(by: \.self)) { element in
            Text("\(element)")
          }
        }
      }
    }
  }
}

enter image description here

Upvotes: 0

mimo
mimo

Reputation: 871

actually the example RPatel99 postet in the earlier response works fine for me:

var data = [[1,2,3],[4,5,6],[7,8,9]]

struct ForTesting : View {
    var body: some View {
        VStack {
            ForEach(data.identified(by: \.self)) { array in
                ForEach(array.identified(by: \.self)) { element in
                    Text("\(element)")
                }
            }
        }
    }
}

But was this your problem?

Upvotes: 1

RPatel99
RPatel99

Reputation: 8096

So I was going to say you should do this to iterate a 2D array:

var data = [[1,2,3],[4,5,6],[7,8,9]]

ForEach(data.identified(by: \.self)) { array in
    ForEach(array.identified(by: \.self)) { element in
        Text("\(element)")
    }
}

but XCode 11 beta is still very buggy with SwiftUI and type inference, so you get a compiler error for doing that, even though it should work. So for now, you'll have to separate everything into functions that the XCode compiler can handle, but with the complex types that SwiftUI uses, it gets ugly very fast. Here is an example:

var data = [[1,2,3],[4,5,6],[7,8,9]]

var body: some View {
    doubleForEach(data: data)
}
func doubleForEach(data: [[Int]]) -> ForEach<IdentifierValuePairs<[[Int]], [Int]>,ForEach<IdentifierValuePairs<[Int], Int>, Text>> {
    return ForEach(data.identified(by: \.self)) { row in
        self.foreach(dataArr: row)
    }
}
func foreach(dataArr: [Int]) -> ForEach<IdentifierValuePairs<[Int], Int>, Text> {
    return ForEach(dataArr.identified(by: \.self)) { data in
        Text("\(data)")
    }
}

Which looks like this:

Upvotes: 2

Related Questions