-4

I wanna display the index of each item in ForEach loop inside SwiftUI views. I tried using an count and increment it everytime but the Xcode gives an error "cannot comform to views"

1 Answers1

7

For Swift Use .enumerated() with array to get index with item in for loop

let array = ["element1", "element2", "element3", "element4"]

for (index,item) in array.enumerated() {
  print(index,item)
}

for SwiftUI this link will help you

Get index in ForEach in SwiftUI

Using Range and Count

struct ContentView: View {
    @State private var array = [1, 1, 2]

    func doSomething(index: Int) {
        self.array = [1, 2, 3]
    }
    
    var body: some View {
        ForEach(0..<array.count) { i in
          Text("\(self.array[i])")
            .onTapGesture { self.doSomething(index: i) }
        }
    }
}
Noman Umar
  • 369
  • 1
  • 7