Austin Berenyi
Austin Berenyi

Reputation: 1053

How do I get the index of an item inside of a ForEach loop?

I have an array of arrays that I'm looping through. The array is structured to represent the 4 quarters of a year:

Q0 January, February, March
Q1 April, May, June
Q2 July, August, September
Q3 October, November December

@State var quarters: [[Month]] = [[.init(name: "January"),.init(name: "February"),.init(name: "March")],
                               [.init(name: "April"), .init(name: "May"), .init(name: "June")],
                               [.init(name: "July"),.init(name: "August"),.init(name: "September")],
                               [.init(name: "October"), .init(name: "November"), .init(name: "December")]]

In the HStack below, I'm trying to append the index of quarter so that I end up with Q0, Q1, Q2, Q3

VStack {

    ForEach (self.quarters, id: \.self) { quarter in
        VStack {
        Spacer()
            HStack {

                Text("Q\(quarter.index)")
                .font(.system(size: 40, weight: .black, design: .rounded))

            }
        }
    }
}

This didn't work. Is there a way I can get the index of the array inside the array of my ForEach loop here? I understand there is a way to retrieve the index if the ForEach loop is using a range as its data set, but I not if the data set is an array.

Upvotes: 2

Views: 1101

Answers (2)

Joakim Danielson
Joakim Danielson

Reputation: 51821

One way to solve this is to look up the elements position in the array

Text("Q\(self.quarters.firstIndex(of: quarter)!)")

Upvotes: 0

E.Coms
E.Coms

Reputation: 11531

You may go this way with an enumerated array:

   struct TempView: View{

   @State var quarters: [[Month]] = [[.init(name: "January", products: ["1", "2"]),.init(name: "February", products: ["1", "2"]),.init(name: "March", products: ["1", "2"])],
[.init(name: "April", products: ["1", "2"]), .init(name: "May", products: ["1", "2"]), .init(name: "June", products: ["1", "2"])]]

  var body: some View {

        ForEach (self.quarters.indices , id: \.self) { (index) in

        VStack {
        Spacer()
            HStack {
                Text("Q\(index)")
                .font(.system(size: 40, weight: .black, design: .rounded))
                Button("TestButton",action: {
                    self.quarters.append([.init(name: "January", products: ["1", "2"]),.init(name: "February", products: ["1", "2"]),.init(name: "March", products: ["1", "2"])])
                })
            }
             Spacer()
        }
    }

 }}                                                                                                

Upvotes: 2

Related Questions