Fix: ForEach Requires RandomAccessCollection Error When Iterating Dictionary in SwiftUI

Written by

in

Quick answer: SwiftUI’s ForEach requires a RandomAccessCollection, but dictionaries are unordered. Fix it by sorting the dictionary into an array of (key, value) tuples with dict.sorted(by:), or by converting keys to an array with Array(dict.keys). Both give ForEach the ordered, indexable collection it needs.

Why this happens

SwiftUI’s ForEach expects its data source to conform to RandomAccessCollection. This protocol guarantees constant-time indexed access and a stable order—both essential for ForEach to diff the collection, animate insertions or deletions, and reuse views efficiently (similar to how UITableView recycles cells).

A Swift Dictionary is explicitly unordered. Its Keys and Values views are lazy collections that do not provide random-access indexing, so they cannot satisfy RandomAccessCollection. When you write ForEach(dict.keys), the compiler emits:

Generic struct 'ForEach' requires that '[String : Int]' conform to 'RandomAccessCollection'

You cannot retroactively make Dictionary conform to RandomAccessCollection because that would violate the type’s semantic contract: dictionary iteration order is undefined and can change between runs.

How to fix it

1. Sort the dictionary into an array of tuples (recommended)

Call sorted(by:) on the dictionary to produce an array of (Key, Value) pairs. The result is a true Array, which conforms to RandomAccessCollection. Use the key as the stable identity for ForEach.

struct ContentView: View {
    let scores = ["Alice": 42, "Bob": 37, "Charlie": 55]

    var body: some View {
        List {
            ForEach(scores.sorted(by: { $0.key < $1.key }), id: \.key) { name, score in
                HStack {
                    Text(name)
                    Spacer()
                    Text("Score: \(score)")
                        .foregroundStyle(.secondary)
                }
            }
        }
    }
}

Why this works: sorted(by:) returns [(String, Int)]. Arrays are random-access, and the key path \.key gives each row a stable identity so SwiftUI can animate changes correctly.

Tip: If you need descending order, flip the comparator: { $0.key > $1.key }. For value-based sorting, use { $0.value < $1.value }.

2. Convert keys to an array and look up values

If you only need the keys in a specific order (for example, alphabetical), materialize the keys view into an array first.

struct ContentView: View {
    let scores = ["Alice": 42, "Bob": 37, "Charlie": 55]

    var body: some View {
        List {
            ForEach(Array(scores.keys).sorted(), id: \.self) { name in
                HStack {
                    Text(name)
                    Spacer()
                    Text("Score: \(scores[name] ?? 0)")
                        .foregroundStyle(.secondary)
                }
            }
        }
    }
}

Trade-off: This adds a dictionary lookup per row (scores[name]). For small dictionaries the cost is negligible; for large or frequently updating data, prefer the tuple approach to avoid repeated hashing.

3. Wrap the logic in a computed property (cleaner view code)

Keep the view body readable by moving the sorting into a computed property.

struct ContentView: View {
    let scores = ["Alice": 42, "Bob": 37, "Charlie": 55]

    private var sortedEntries: [(String, Int)] {
        scores.sorted { $0.key < $1.key }
    }

    var body: some View {
        List {
            ForEach(sortedEntries, id: \.0) { name, score in
                HStack {
                    Text(name)
                    Spacer()
                    Text("Score: \(score)")
                }
            }
        }
    }
}

This pattern also makes it trivial to add filtering or debounced updates later.

How to prevent it

  • Default to arrays for UI data. If the order matters on screen, store an array of identifiable models instead of a dictionary.
  • Use Identifiable models. Define a small struct struct Player: Identifiable { let id = UUID(); let name: String; let score: Int } and keep [Player]. ForEach(players) then works without any id: parameter.
  • Sort once, not every frame. Move sorting out of the body getter (as in the computed property example) so SwiftUI doesn’t re-sort on every render pass.
  • Avoid Dictionary as a single source of truth for lists. Dictionaries are great for O(1) lookups by key; arrays are great for ordered presentation. Convert at the boundary.

FAQ

Can I make Dictionary conform to RandomAccessCollection with an extension?

No. RandomAccessCollection requires a stable, integer-indexable order. Dictionary iteration order is explicitly undefined and can change when the dictionary mutates. Conforming would break the protocol’s semantic guarantees and cause undefined behavior in ForEach.

Why does ForEach(dict.keys.sorted()) still error without Array(...)?

dict.keys.sorted() returns [Key]—an array—so it actually works. The error in the original question came from passing dict.keys directly (a Dictionary.Keys view) or the dictionary itself. Wrapping with Array(...) or calling .sorted() both materialize an array.

What if the dictionary changes at runtime?

Recompute the sorted array whenever the dictionary changes. If the dictionary lives in an @Observable class or @State, the view will re-evaluate body and the computed property will produce a fresh sorted array, triggering ForEach diffing and animations automatically.


Need to display dictionary data in a SwiftUI list? Sort it into an array of tuples or materialize the keys—both give ForEach the ordered, random-access collection it requires.

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.