Reputation: 475
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
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
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)")
}
}
}
}
}
}
Upvotes: 0
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
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