Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 46 ยท Views and Layout

List, ForEach and Identifiable

Show collections in SwiftUI with List and ForEach. Learn Identifiable and stable ids, sections, swipe actions, pull to refresh and when to use LazyVStack and LazyVGrid.

Almost every app shows a collection: messages, products, settings, photos. In SwiftUI you describe one row, then ask the framework to repeat it for each item in your data. Two views do the repeating. ForEach produces a view for every element of a collection, and List is a scrolling container with the platform's standard row styling. The thing that makes this work correctly, especially when data changes, is identity.

This lesson covers List and ForEach, why elements need an id, sections and swipe actions, pull to refresh, and the lazy containers (LazyVStack, LazyVGrid) for custom scrolling layouts. SwiftUI code is read-only on this site; the runnable examples are Swift models of the identity diff and of lazy loading. If stacks are still new to you, see VStack, HStack, ZStack and Spacer first.

Repeating views from data

List Scrolling rows with the standard look.
ForEach Builds one view per element.
Identifiable Gives each element a stable id.

Identity lets SwiftUI tell items apart when data changes.

1 / 2

List and ForEach

The simplest list shows a collection directly. Each element needs an identity, which is why the model conforms to Identifiable:

Swift
struct Todo: Identifiable {
    let id: UUID
    var title: String
    var isDone: Bool
}

struct TodoListView: View {
    let tasks: [Todo]

    var body: some View {
        List(tasks) { task in
            Text(task.title)
        }
    }
}

List(tasks) { ... } is a shortcut for a List containing a ForEach. You can write the long form when a list mixes static and dynamic rows:

Swift
List {
    Text("Today")
    ForEach(tasks) { task in
        Text(task.title)
    }
}

ForEach is not a container with a look of its own: it simply produces child views, so it works inside a List, a VStack or a LazyVGrid. Only List gives you scrolling, separators and swipe behaviour. A ForEach in a plain VStack does not scroll by itself and builds every row up front.

Identity: the id

SwiftUI has to know which element is which, so that when your array changes it can insert, remove or move rows instead of rebuilding them all. You provide that identity in one of two ways:

  • Conform the element to Identifiable and give it an id property that is stable and unique.
  • Pass a key path: ForEach(names, id: \.self) uses the value itself as the id. That is safe only if the values are unique and rarely change.

The rule that trips up beginners is stability. An id must belong to the data, not to the moment the view is drawn.

Swift
struct Bad: Identifiable {
    var id: UUID { UUID() }     // a NEW id every time it is read: wrong
}

struct Good: Identifiable {
    let id = UUID()             // created once, stored: correct
}

With the first version every redraw looks to SwiftUI like all rows were deleted and brand-new rows appeared. Scroll position, animations and any row-local state are lost. Prefer an id from your database or server; if you must generate one, create it once when the item is created.

This Swift model reproduces the comparison SwiftUI makes. Given the old and new arrays, it finds removed, inserted, updated and moved items by id.

Swift Diffing a list by id

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Case 4 is the unstable-id bug in numbers: the titles are identical, yet every row counts as removed and re-inserted.

Sections, swipe actions and refresh

Group rows with Section, which adds a header (and optionally a footer):

Swift
List {
    Section("Open") {
        ForEach(open) { task in Text(task.title) }
    }
    Section("Done") {
        ForEach(done) { task in Text(task.title) }
    }
}

Rows can offer actions on swipe. The .swipeActions modifier takes the edge and a set of buttons; a button with the .destructive role is drawn red and, for a full swipe, runs without a further tap.

Swift
ForEach(tasks) { task in
    Text(task.title)
        .swipeActions(edge: .trailing) {
            Button(role: .destructive) {
                store.delete(task)
            } label: {
                Label("Delete", systemImage: "trash")
            }
        }
}

For the classic "edit mode" with delete and reorder handles, attach .onDelete { offsets in ... } and .onMove { source, destination in ... } to the ForEach; they hand you index sets to apply to your array.

Pull to refresh is one modifier on the List. Its closure is async, and the spinner stays visible until the closure returns:

Swift
List(tasks) { task in
    Text(task.title)
}
.refreshable {
    await store.reload()
}

A List takes its look from the platform and its style (.plain, .insetGrouped, and others). If you need full control over rows, spacing and backgrounds, a lazy stack inside a ScrollView is the alternative.

Lazy containers

A List creates row views lazily as they approach the screen. A regular VStack inside a ScrollView does not: it builds every child immediately, which is slow for thousands of rows. Swap in a lazy container when you want a custom look but still need efficiency:

Swift
ScrollView {
    LazyVStack(spacing: 12) {
        ForEach(photos) { photo in
            PhotoRow(photo: photo)
        }
    }
    .padding()
}

For a grid, LazyVGrid takes column descriptions. .adaptive(minimum:) asks for as many columns as fit when each is at least that wide, which makes the grid reflow between phone and iPad and between portrait and landscape:

Swift
let columns = [GridItem(.adaptive(minimum: 100), spacing: 8)]

ScrollView {
    LazyVGrid(columns: columns, spacing: 8) {
        ForEach(photos) { photo in
            PhotoCell(photo: photo)
        }
    }
}

The model below estimates how many rows get created, and how many grid columns fit. The lazy window is simplified: real SwiftUI decides its own buffer size, so only the idea carries over.

Swift Lazy versus eager, and adaptive columns

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why must each element in a ForEach have an id?

    Identity lets SwiftUI insert, remove and move specific rows, and keep per-row state and animations, instead of rebuilding everything.
  2. 2. What is wrong with var id: UUID { UUID() } in an Identifiable struct?

    A computed property returns a different value on every access. The id must be created once and stored, like let id = UUID().
  3. 3. When is LazyVStack inside a ScrollView a good choice?

    Lazy stacks build rows on demand, which keeps long custom-styled lists efficient.
  4. 4. What does .refreshable { await store.reload() } do on a List?

    The refreshable modifier adds the pull gesture and keeps the spinner visible until the async closure finishes.

Summary

  • ForEach repeats a view per element; List adds scrolling, separators and standard row behaviour.
  • Elements need a stable, unique id: conform to Identifiable or pass id: with a key path.
  • Never compute a fresh id on each read; unstable ids make every row look new.
  • Use Section for groups, .swipeActions for row buttons, .onDelete and .onMove for editing, and .refreshable for pull to refresh.
  • LazyVStack and LazyVGrid build only what is near the screen; a plain VStack builds everything.

Next, add interaction with Buttons, Toggles, Sliders and Pickers.