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?
answer
- nest two ForEach loops
- Section with a header closure
- deletion lives on the ForEach
- offsets, not identifiers
basics
~20 sBuild 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 sA `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 linesimport 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
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.
Explain why onDelete is a ForEach modifier (DynamicViewContent), what the IndexSet means per section, and when editActions on a bound array replaces the closure.
Show the offsets trap with filtered or sorted data, delete by identifier through the model, and use deleteDisabled for rows that must not go.
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