How to use SwiftUI ForEach with index

In order to create views from a collection of data we use ForEach in SwiftUI. Sometimes we need index of current element in ForEach, we can use range, indices or enumerated() method.

ForEach Index using enumerated()

If we want to access both index and element in closure then enumerated() method can help us to achieve this. Let us see an example to display a list with indices:

let fruits = ["Apple", "Orange", "Banana", "Mango"]

    var body: some View {
        VStack {
            ForEach(Array(fruits.enumerated()), id: \.element) { index, fruit in
                Text("Index \(index): \(fruit)")
            }
        }
    }

  • Array(fruits.enumerated()) creates a tuple array. And an element of this tuple looks like ‘(offset:Int, element:String)’
  • We use the offset as unique identifier for each element.
  • Using enumerated() provides both index and item (fruit) in the ForEach closure.

ForEach index using indices property

We can get index for each item using indices property of an array. Here is an example that how we can do this:

let animals = ["Lion", "Bear", "Fox"]
    
    var body: some View {
        List {
            ForEach(animals.indices, id: \.self) { index in
                HStack {
                    Text("\(index + 1).")
                    Text(animals[index])
                }
            }
        }
    }

Indices property provides us a ranges of indices, we can use index in closure as per our need and can fetch current item (animal) with index.

ForEach Index using range

In case we need to iterate over a loop for a specific number of times, we can define range from 0 to required length as 0…<requiredNumber. The required number could be length or count of an array. For example:

let items = ["Item 1", "Item 2", "Item 3", "Item 4"]
    
    var body: some View {
        List {
            ForEach(0..<items.count, id: \.self) { index in
                HStack {
                    Text("\(index + 1).")
                    Text(items[index])
                }
            }
        }
    }

Note: ‘\.self’ means use index as unique identifier.

Leave a Reply

Your email address will not be published. Required fields are marked *