How to get index in Foreach in SwiftUI

SwiftUI ForEach

Posted on 7 Dec 2023 . 3 min read


In SwiftUI, the ForEach is used to iterate over a collection of data and create views dynamically based on that data. If you need the index of the current element while using ForEach, you can achieve this by using the following ways along with ForEach:


#Using range and count

If you want to use a range of indices with a count in SwiftUI’s ForEach loop, you can create a Range and iterate through it. Here's an example:

import SwiftUI

struct ContentView: View {
    let items = ["Milk", "Bread", "Cookies", "Tea"]

    var body: some View {
        VStack {
            ForEach(0..<items.count, id: \.self) { index in
                Text("\(index): \(items[index])")
            }
        }
    }
}


In this example:

  • 0..<items.count creates a range of indices from 0 to items.count - 1.
  • ForEach uses this range of indices. id: \.self is used to identify each element uniquely.
  • Inside the ForEach loop, items[index] is used to access each item using the index.


This method allows you to iterate through a range of indices based on the count of your collection and access the elements within the ForEach loop in SwiftUI.


#Using indices property

In SwiftUI, you can use the indices property of a collection to access the indices while iterating through the elements using ForEach. Here's an example of how you can use indices to get the index within a ForEach loop. Here’s an example:

import SwiftUI

struct ContentView: View {
    let items = ["Milk", "Bread", "Cookies", "Tea"]

    var body: some View {
        VStack {
            ForEach(items.indices, id: \.self) { index in
                Text("\(index): \(items[index])")
            }
        }
    }
}


In this example:

  • items.indices gives you a range of indices for the items array.
  • ForEach uses this range of indices. id: \.self is used to identify each element uniquely.
  • Inside the ForEach loop, items[index] is used to access each item using the index.


This approach allows you to iterate through the indices of the collection and use those indices to access the elements within the ForEach loop in SwiftUI.


#Using enumerated() method

If you need the index of the current element while using ForEach, you can achieve this by using the enumerated() method along with ForEach. Here’s an example:

import SwiftUI

struct ContentView: View {
    let items = ["Milk", "Bread", "Cookies", "Tea"]

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


In this example:

  • enumerated() is used to get a sequence of pairs (index, value) from the items array.
  • Array(items.enumerated()) converts the enumerated sequence into an array of tuples.
  • ForEach iterates through this array of tuples, where index and item represent the index and value, respectively.
  • id: \.1 is used to specify a unique identifier for each row in the ForEach loop. \0 refers to the first element of the tuple (which is the index) and \1 refers to the second element (which is the item).


This way, you can access the index and item simultaneously within the ForEach loop in SwiftUI.


Don’t hesitate to contact me if you have any questions or queries. Follow me on twitter @gurjitpt for any updates.

Thanks!


Share this article



Written By

Generic placeholder image

Gurjit Singh

I’m Computer Science graduate and an iOS Engineer who writes about Swift and iOS development. Follow me for more updates:


Discover articles by topics

SwiftUI Class Struct Networking XCode NSCache Enum Optionals Property Observers Closures Guard Reviews StoreKit App Store Algorithms Testing Operators Protocol Extensions Weak Unowned SwiftData WWDC23 GCD API Admob SwiftLint Lottie Foreach Objective-C UIKit NavigationSplitView

Related Articles


Deep Dive into Autorelease Pools in Swift

In the realm of software development, memory management plays a crucial role in ensuring the efficient allocation and deallocation of memory...

2024-01-28 . 4 min read     Swift Autorelease

Read More »

Swift enum equatable: with or without associated values

Swift enums provide a powerful way to model a set of related values. Enums can be equipped with associated values, allowing them to represen...

2024-01-24 . 3 min read     Swift Enums

Read More »

How to create Date Picker in SwiftUI

Use a DatePicker when creating a view that enables users to choose both a calendar date and, if needed, a specific time.In SwiftUI, you can ...

2024-01-16 . 2 min read     SwiftUI DatePicker

Read More »

Getting started with Swiftlint to enforce Swift style

SwiftLint is a tool that ensures Swift code adheres to defined style guidelines. It automates code review by identifying and suggesting impr...

2023-12-29 . 4 min read     Swift SwiftLint

Read More »

How to use Lottie animation in SwiftUI

Lottie is a fantastic tool for incorporating high-quality animations into your SwiftUI projects. There are several ways to add Lottie to pro...

2023-12-13 . 2 min read     SwiftUI Lottie

Read More »

How to implement navigation split view in SwiftUI

n SwiftUI, the NavigationView and SplitView allow you to create split-screen layouts, especially useful for iPad applications....

2023-11-30 . 2 min read     NavigationSplitView

Read More »