3

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.

1 Answer 1

5

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)
    }
}
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you. I tried it and get the following error: "Cannot subscript a value of incorrect or ambiguous type". The compiler marks the array[index]
You need to note that a lot of times you have different errors than what XCode shows you when dealing with SwiftUI. index is Int so this error should not be valid.
You are right, I had to close XCode and restart, then clean the project and the error disappeared. Thank you!
I receive a warning for a similar syntax: ForEach(0..<array.endIndex) "Non-constant range: argument must be an integer literal"
@AlessandroMascolo add an id: \.self argument to your ForEach initializer if your array isn’t constant.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.