skip to content

Sections, Rows and Editing

List and ForEach turn data into rows with sections, swipe actions, selection and edit mode. Interviewers ask how a list supports delete and reorder and why a row redraws too often.

on this pageshow

explore

questions

5

In SwiftUI, how do you show a mail inbox grouped by day in a List with Section headers, and let people swipe to delete a message?

level: juniorimportance: must knowfreq 78%

answer

  1. nest two ForEach loops
  2. Section with a header closure
  3. deletion lives on the ForEach
  4. offsets, not identifiers

basics

~20 s

Build the List from a ForEach over the days, wrap each day's ForEach of messages in a Section with a header, and attach onDelete(perform:) to that inner ForEach; SwiftUI adds swipe to delete and hands you the row offsets.

solid answer

~40 s

A `List` takes a `ForEach` over the days, and each day becomes `Section { … } header: { Text(day.title) }` around a second `ForEach` over that day's messages. Swipe to delete comes from `onDelete(perform:)`, which SwiftUI declares on `DynamicViewContent` — in practice a `ForEach` — and not on `List`, so `List(messages) { … }.onDelete` does not compile. The closure receives an `IndexSet` of offsets into that `ForEach`'s own collection, so in a sectioned inbox each day's `ForEach` carries its own `onDelete` and removes from that day's array, usually with `remove(atOffsets:)`. The same modifier gives the list its delete controls in edit mode, and `deleteDisabled(_:)` exempts single rows.

code

swift · 27 lines
swift
import SwiftUI

struct Message: Identifiable { let id = UUID(); var subject: String }
struct Day: Identifiable { let id = UUID(); var title: String; var messages: [Message] }

struct InboxView: View {
    @State private var days: [Day] = []

    var body: some View {
        List {
            ForEach($days) { $day in
                Section {
                    ForEach(day.messages) { message in
                        Text(message.subject)
                    }
                    .onDelete { offsets in
                        day.messages.remove(atOffsets: offsets)
                    }
                } header: {
                    Text(day.title)
                } footer: {
                    Text("\(day.messages.count) messages")
                }
            }
        }
    }
}

go deeper

for a junior

Recall the shape: List, an outer ForEach of days, a Section with a header, an inner ForEach of messages, and onDelete on that inner ForEach removing the offsets.

for a middle

Explain why onDelete is a ForEach modifier (DynamicViewContent), what the IndexSet means per section, and when editActions on a bound array replaces the closure.

for a senior

Show the offsets trap with filtered or sorted data, delete by identifier through the model, and use deleteDisabled for rows that must not go.

for a principal

Set a team rule that list deletions go through the model by identifier, so derived arrays, sync and undo never act on stale positions.

## The three building blocks A SwiftUI **`List`** is a scrolling, single-column container of rows. Apple's documentation describes it as loading rows as needed, which makes it suitable for long collections such as an inbox. Three types do the work: - **`List`** — the container. It can take static rows, a collection directly (`List(messages) { … }`), or a builder that mixes static views and `ForEach` loops. - **`ForEach`** — turns a collection of `Identifiable` values (or values plus an `id:` key path) into one row view per element. - **`Section`** — groups rows and adds an optional header and footer. Its current initializers take trailing closures: `Section { rows } header: { … } footer: { … }`, or `Section("Today") { … }` for a plain text title. For an inbox grouped by day, the data is naturally two-level: an array of days, each holding an array of messages. The view mirrors that shape with two nested `ForEach` loops. ```swift List { ForEach($days) { $day in Section { ForEach(day.messages) { message in Text(message.subject) } .onDelete { offsets in day.messages.remove(atOffsets: offsets) } } header: { Text(day.title) } } } ``` The outer `ForEach` iterates a binding (`$days`) so each section can write back to its own day's `messages` array. ## Swipe to delete with onDelete(perform:) `onDelete(perform:)` is declared in an extension on **`DynamicViewContent`**, the protocol that `ForEach` conforms to. Attaching it does three things: 1. On iOS, every row produced by that `ForEach` gains a trailing **swipe-to-delete** action. 2. When **edit mode** is active (for example, after an `EditButton` is tapped), the same rows show delete controls. 3. When someone deletes, SwiftUI calls your closure with an **`IndexSet`** of the deleted rows' positions. The closure is where the data changes; SwiftUI does not remove anything for you. `remove(atOffsets:)`, which SwiftUI adds to mutable, range-replaceable collections, makes the call a one-liner. Because the modifier lives on `DynamicViewContent`, attaching it to `List` is a compile error: the compiler reports that the `List` type has no member `onDelete`. Even a list built with `List(messages) { … }` needs an explicit `ForEach` inside a builder to get deletion. ## Offsets are positions, not identifiers The `IndexSet` holds **positions in the collection that particular `ForEach` iterates**. Two consequences matter in a real inbox: - In a **sectioned** list every inner `ForEach` has its own `onDelete`, and its offsets index that day's array only. One handler for the whole list would not know which day was swiped. - If a `ForEach` iterates a **derived** array — `messages.filter { $0.isUnread }` or a sorted copy — the offsets index that derived array. Deleting those offsets from the source array removes the wrong messages. Map offsets to identifiers first (`offsets.map { filtered[$0].id }`) and delete by identifier. A single row can opt out with **`deleteDisabled(_:)`**, for example a message that is still sending. ## Variations worth knowing | Need | API | Note | |---|---|---| | Section title and count | `Section { … } header: { … } footer: { … }` | footer sits below the rows | | Change the list's look | `listStyle(_:)` with `.insetGrouped`, `.plain`, `.grouped`, `.sidebar` | applies to lists inside the view | | Delete without writing the closure | `List($messages, editActions: .delete) { $message in … }` | iOS 16; the array must be range-replaceable | | Delete plus reorder in edit mode | `onDelete` and `onMove(perform:)` on the same `ForEach` | add an `EditButton` to toggle edit mode | The `editActions:` form, available from iOS 16, applies deletions to the bound array itself. `EditActions.delete` is only available when the collection conforms to `RangeReplaceableCollection`, and `.move` only when it conforms to `MutableCollection`. ## Mistakes that show up in review - Putting `onDelete` on the `List` or on a row view: it belongs on the `ForEach`. - Writing one handler for a sectioned list and deleting from a flattened array. - Deleting source-array offsets while the `ForEach` iterates a filtered copy. - Forgetting that the closure must actually mutate the data; the swipe animation alone does not remove a message from your model. - Identifying messages by subject line instead of a stable identifier; how SwiftUI uses those identifiers is the subject of the lesson on view identity.

  • Your inbox ForEach shows only unread messages through a filter; how do you delete safely?
    The `IndexSet` indexes the filtered array the `ForEach` iterates, not the source. Convert first: `let ids = offsets.map { unread[$0].id }`, then remove from the source with `messages.removeAll { ids.contains($0.id) }`. Deleting the raw offsets from `messages` would remove whichever messages happen to sit at those positions in the unfiltered array.
  • When would you choose List($messages, editActions: .delete) over onDelete?
    When the rows come straight from a mutable array you own and deleting simply removes the element. From iOS 16, `editActions:` applies the change to the bound array, so there is no closure to get wrong. Keep `onDelete` when deletion must go through a model, a server call or an undo step, or when the `ForEach` shows a derived array.

  • onDelete can be attached directly to a List built from an array
  • The IndexSet contains the identifiers of the deleted messages
  • SwiftUI removes the row from your array automatically after a swipe
  • One onDelete on the outer ForEach of days reports which messages were deleted
  • Offsets from a filtered ForEach can be removed from the source array
open as a page

In SwiftUI, how do List selection, EditButton and the editMode environment value work together so iPhone users can multi-select inbox messages?

level: middleimportance: must knowfreq 66%

basics

~20 s

Bind List(selection:) to a Set of the rows' ID type; on an iPhone, tap multi-selection works only in edit mode, which EditButton toggles through the editMode environment value that your own views can read or own.

open as a page

In a SwiftUI List, how do swipeActions differ from onDelete, and why does swipe to delete vanish once you add an Archive swipe action?

level: middleimportance: must knowfreq 64%

basics

~10 s

onDelete gives every row one built-in Delete; swipeActions(edge:allowsFullSwipe:content:) lets you supply your own buttons per edge. Once a row has swipe actions, SwiftUI stops synthesizing the Delete, so you add a destructive Button yourself.

open as a page

In SwiftUI, how do listStyle and the row modifiers listRowInsets, listRowSeparator and listRowBackground shape a List, and where must each one go?

level: middleimportance: should knowfreq 42%

basics

~20 s

listStyle(_:) picks the whole list's look, while listRowInsets, listRowSeparator and listRowBackground are row settings the containing List reads from each row view, so they go on the row's outermost view, not on a nested subview.

open as a page

On iOS 27, how do SwiftUI's reorderable() and reorderContainer(for:isEnabled:move:) differ from onMove when a mail client lets people drag its folders into a new order?

level: seniorimportance: should knowfreq 32%

basics

~20 s

onMove gives a List's ForEach index-based moves; iOS 27's reorderable() marks a ForEach movable inside any list, stack, grid or layout carrying reorderContainer(for:isEnabled:move:), whose closure gets a ReorderDifference of item IDs and a before-or-end destination.

open as a page