-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"

3
  • Hard to know what exactly you are asking about without code but maybe you are looking for enumerated() Commented Dec 9, 2021 at 8:33
  • Either iterate the indices of the array or enumerate the array Commented Dec 9, 2021 at 8:34
  • please share your code example to understand what you are doing and where's the issue Commented Dec 9, 2021 at 8:35

1 Answer 1

9

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.