Apr 30, 2024 iOS

How to get the index of the element in the List in SwiftUI when the List is populated with the array?

Certainly! In SwiftUI, you can use the enumerated() function to get the index when looping through a List. Let’s explore how to achieve this:

Suppose you have an array of items that you want to display in a List along with their corresponding indices. Here’s how you can do it:

import SwiftUI

struct ContentView: View {
    let items = ["Apple", "Banana", "Cherry", "Date"]

    var body: some View {
        List {
            ForEach(Array(items.enumerated()), id: \.1) { (index, item) in
                Text("\(index): \(item)")
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

In this example:

  • We use Array(items.enumerated()) to create a sequence of pairs containing the index and the item.
  • The ForEach loop iterates through this sequence, and we extract the index and item using (index, item) in the closure.
  • The id: \.1 ensures that SwiftUI uses the item itself as the identifier for each row.

Now your List will display each item along with its corresponding index.

To get the index of an element in a List in SwiftUI when the List is populated with an array, you can use the enumerated() method of the array. Here’s how you can achieve this:

import SwiftUI

struct ContentView: View {
    let items = ["Item 1", "Item 2", "Item 3", "Item 4"]

    var body: some View {
        List {
            ForEach(Array(items.enumerated()), id: \.element) { index, item in
                Text(item)
                    .onTapGesture {
                        // Access the index of the tapped item
                        print("Tapped item at index \(index)")
                    }
            }
        }
    }
}

In this example:

  • We have an array named items containing some strings.
  • We use a List with a ForEach loop to iterate over each element of the items array.
  • We use the enumerated() method to get the index and element pair for each item in the array.
  • We use Array(items.enumerated()) to convert the enumerated sequence into an array to conform to the ForEach initializer requirements.
  • Inside the ForEach, we use .onTapGesture to handle tap events on each item and print the index of the tapped item.

This way, you can access the index of each element in the list when it’s tapped. Adjust the actions inside .onTapGesture according to your requirements.