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"
Asked
Active
Viewed 4,039 times
-4
-
Hard to know what exactly you are asking about without code but maybe you are looking for [enumerated()](https://developer.apple.com/documentation/swift/array/1687832-enumerated) – Joakim Danielson Dec 09 '21 at 08:33
-
Either iterate the `indices` of the array or `enumerate` the array – vadian Dec 09 '21 at 08:34
-
please share your code example to understand what you are doing and where's the issue – Muhammad Nawaz Dec 09 '21 at 08:35
1 Answers
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