wildfang
wildfang

Reputation: 335

SwiftUI ForEach get element AND index in 2d array

I need to access the index as well as the element in a ForEach loop.

So far, I have in my data store:

@Published var sevenDayReview: [[CGFloat]] = [
        [1754,1654],[1854,1687],[1985,1854],[1765,1652],[1864,1698],[1987,1654],[1865,1465]
    ]

and in my view:

ForEach(self.dataModel.sevenDayReview, id: \.self) { array in
       ForEach(array, id: \.self) { element in
             VStack {
                    ReviewChart(dataModel: CalorieViewModel(), valueHeight: element, cornerRadius: 5, color: 2 )
              }
       }
}

which is working fine. But I want to pass the current array index of the current element to the color parameter.

Background: Load a bar chart with values from the datastore and alternate the colors by row index.

I can't figure out what the best way to do this is in SwiftUI.

Upvotes: 3

Views: 7041

Answers (1)

iSpain17
iSpain17

Reputation: 3053

You can use a different init of the ForEach view:

ForEach(0..<array.endIndex) { index in //inner ForEach
    VStack {
        ReviewChart(dataModel: CalorieViewModel(), 
                    valueHeight: array[index], 
                    cornerRadius: 5, 
                    color: index)
    }
}

Upvotes: 5

Related Questions