2

I wish to utilise the index from the items in ForEach. This is regarding the post I made here where I have now changed the buttonTitles into a list of struct from a dictionary. However I can't seem to do the usual .enumerated() method in ForEach with [struct].

struct ButtonObject: Hashable{
    let id =  UUID()
    var name: String
    var isSelected: Bool

}


class SomeData: ObservableObject{
    @Published var buttonObjects: [ButtonObject] = [ButtonObject(name: "tag1", isSelected: false),
                                                   ButtonObject(name: "tag2", isSelected: false), ButtonObject(name: "tag3", isSelected: false)]
}



struct someData3: View {
    @ObservedObject var someData = SomeData()

    var body: some View {
        VStack{
            ForEach(Array(someData.buttonObjects.enumerated()), id: \.element.id)){ind, object in
                HStack{
                    Text(ind)
                    Text(object.name)
                }
            }




        }

    }
}
mic
  • 155
  • 2
  • 9
  • 1
    Does this answer your question? [How do you use .enumerated() with ForEach in SwiftUI?](https://stackoverflow.com/questions/59295206/how-do-you-use-enumerated-with-foreach-in-swiftui) – pawello2222 Jun 15 '20 at 08:27

1 Answers1

3

Here is fixed part

ForEach(Array(someData.buttonObjects.enumerated()), id: \.element.id) { ind, object in
    HStack{
        Text("\(ind)")
        Text(object.name)
    }
}
Asperi
  • 228,894
  • 20
  • 464
  • 690