How to Get an Element’s Index Inside ForEach in SwiftUI

How to Get an Element's Index Inside ForEach in SwiftUI

Written by

in

Quick answer: To get both the index and element in a SwiftUI ForEach, iterate over items.enumerated() (or Array(items.enumerated()) prior to Swift 6.2) with id: \.element.id for Identifiable models or id: \.offset for plain values. Avoid ForEach(0..<array.count) without an id parameter, because SwiftUI treats bare integer ranges as static and stops updating rows when the array changes.

Why this happens

SwiftUI’s standard ForEach initializers pass only the collection’s element into the view-builder closure, leaving you without the element’s integer position when you need to display row numbers or pass an index to an action handler.

When developers work around this by writing ForEach(0..<array.count) { index in ... }, they hit a subtle trap. ForEach has a dedicated initializer that accepts Range<Int> without an id parameter, and SwiftUI treats that overload as a constant range. Xcode warns about this with Non-constant range: not an integer range or Non-constant range: argument must be an integer literal.

Because SwiftUI assumes a bare Range<Int> never changes, mutating the underlying @State array—especially replacing values while array.count stays the same—can leave stale views on screen or trigger out-of-bounds crashes when items are removed. Choosing the right dynamic ForEach pattern fixes both problems.

How to fix it

1. Use enumerated() with an explicit id (Recommended)

Calling enumerated() on your array yields (offset, element) pairs, giving you both the zero-based counter and the value at the same time without subscripting back into the array inside the view body.

In Swift 6.2 and later (via SE-0459), EnumeratedSequence conforms to RandomAccessCollection whenever the base collection does. That means you can pass items.enumerated() directly into ForEach:

import SwiftUI

struct TaskItem: Identifiable {
    let id = UUID()
    var title: String
}

struct TaskListView: View {
    @State private var tasks = [
        TaskItem(title: "Configure signing"),
        TaskItem(title: "Run unit tests"),
        TaskItem(title: "Upload archive")
    ]

    var body: some View {
        List {
            ForEach(tasks.enumerated(), id: \.element.id) { index, task in
                Button("\(index + 1). \(task.title)") {
                    markSelected(at: index)
                }
            }
        }
    }

    private func markSelected(at index: Int) {
        tasks[index].title += " ✓"
    }
}

If your project builds with an earlier Swift version (prior to Swift 6.2), EnumeratedSequence only conforms to Sequence, whereas ForEach requires RandomAccessCollection. Wrap the sequence in Array(...) so it compiles:

ForEach(Array(tasks.enumerated()), id: \.element.id) { index, task in
    Button("\(index + 1). \(task.title)") {
        markSelected(at: index)
    }
}

Notice id: \.element.id. Keying off the model’s stable Identifiable ID tells SwiftUI to track each row by the item itself rather than its slot in the array. Insertions, deletions, and move animations all work reliably.

If you are iterating over primitive values that can contain duplicates—such as [1, 1, 2]—and do not conform to Identifiable, key off \.offset instead:

import SwiftUI

struct NumberListView: View {
    @State private var array = [1, 1, 2]

    var body: some View {
        VStack(spacing: 12) {
            ForEach(Array(array.enumerated()), id: \.offset) { index, number in
                Text("Index \(index): \(number)")
                    .onTapGesture {
                        doSomething(index: index)
                    }
            }
        }
    }

    private func doSomething(index: Int) {
        array = [1, 2, 3]
    }
}

When array changes from [1, 1, 2] to [1, 2, 3], SwiftUI re-evaluates the view body for each offset and updates the Text labels immediately.

2. Use array.indices with id: \.self

If you prefer subscripting the array by index, iterate over array.indices rather than 0..<array.count, and always pass id: \.self:

import SwiftUI

struct IndicesExampleView: View {
    @State private var array = [1, 1, 2]

    var body: some View {
        VStack(spacing: 12) {
            ForEach(array.indices, id: \.self) { index in
                Text("\(array[index])")
                    .onTapGesture {
                        doSomething(index: index)
                    }
            }
        }
    }

    private func doSomething(index: Int) {
        array = [1, 2, 3]
    }
}

Adding id: \.self forces SwiftUI to pick the generic RandomAccessCollection initializer instead of the static Range<Int> initializer. SwiftUI now treats the range dynamically and refreshes child views whenever array mutates.

Be careful with this approach if your list supports swipe-to-delete or animated removals. Because each row’s identity is its integer index (0, 1, 2), deleting an item while SwiftUI animates a transition or fires a delayed closure can evaluate array[index] against the shortened array and crash with Fatal error: Index out of range. Keep array.indices for non-destructive mutations or fixed-length collections.

3. Pass a Binding to ForEach if you only need to mutate the item

In many SwiftUI views, the only reason you want an index is to mutate array[index] inside a Toggle, TextField, or button action. You do not need an index for that at all. Pass $array directly to ForEach to get a Binding to each Identifiable element:

import SwiftUI

struct ChecklistItem: Identifiable {
    let id = UUID()
    var name: String
    var isComplete = false
}

struct ChecklistView: View {
    @State private var items = [
        ChecklistItem(name: "Update build number"),
        ChecklistItem(name: "Check release notes")
    ]

    var body: some View {
        List {
            ForEach($items) { $item in
                HStack {
                    Toggle(item.name, isOn: $item.isComplete)
                    Button("Reset") {
                        item.isComplete = false
                    }
                }
            }
        }
    }
}

Using ForEach($items) avoids manual index lookups, keeps animations tied to ChecklistItem.id, and eliminates index-out-of-range bugs when rows are added or deleted.

4. Use zip when iterating over an ArraySlice

enumerated() always counts offset starting from 0, even when the collection’s startIndex is not zero. For example, if you take let slice = items.dropFirst(2), its first valid index is 2, while slice.enumerated() still reports offset as 0. Passing that 0 into slice[index] crashes at runtime.

When working with slices or collections that do not guarantee zero-based indexing, pair indices with the collection using zip:

import SwiftUI

struct SliceListView: View {
    let items: [TaskItem]

    var body: some View {
        let remainingItems = items.dropFirst(1)

        List {
            ForEach(Array(zip(remainingItems.indices, remainingItems)), id: \.1.id) { index, item in
                Text("Original index \(index): \(item.title)")
            }
        }
    }
}

Here, index is guaranteed to be a valid subscript index on remainingItems (and on the parent items array), while \.1.id preserves stable element identity.

How to prevent it

  • Never pass a dynamic count to ForEach(0..<array.count) without id: \.self. Reserve unkeyed integer ranges strictly for compile-time literals such as ForEach(0..<3).
  • Conform row models to Identifiable whenever possible. Using id: \.element.id with enumerated() keeps SwiftUI animations, state preservation, and swipe actions accurate when array contents shift.
  • Prefer ForEach($items) for editable rows. If you are not displaying the row number in the UI, binding directly to the element removes index management altogether.
  • Guard index bounds in asynchronous callbacks. If a tap triggers an async task that mutates array[index] later, look up the item by its id (array.firstIndex(where: { $0.id == item.id })) after await rather than trusting a captured integer index.

FAQ

Why does ForEach(array, id: \.self) duplicate or glitch when two elements have the same value?

When you use id: \.self on an array like [1, 1, 2], two elements share the identifier 1. SwiftUI requires every ID in a ForEach container to be unique; duplicate IDs cause SwiftUI to reuse the wrong view state or misrender updates. Wrap the values in an Identifiable struct with a unique UUID, or use enumerated() with id: \.offset if positional identity is acceptable.

Does Array(items.enumerated()) hurt performance in SwiftUI?

For typical UI lists of dozens or hundreds of rows, allocating the lightweight (offset, element) array takes microseconds and has no noticeable impact—especially when items holds small structs or reference types. Starting in Swift 6.2, you can drop the Array(...) wrapper completely and pass items.enumerated() straight to ForEach with zero extra allocation.

Why do I get Fatal error: Index out of range when deleting a row with ForEach(array.indices, id: \.self)?

During a removal animation or list diff pass, SwiftUI may briefly evaluate existing row closures before tearing down the removed view, or a button closure may hold an outdated captured index. Switch to Identifiable models and delete items using List‘s .onDelete modifier or array.removeAll { $0.id == item.id } instead of subscripting array[index] directly.

Sources & credits

Parts of this guide are adapted from content licensed under CC BY-SA 4.0; this article is shared under the same license.