SwiftUI List and ForEach: Row Identity, Sections, Delete and Move
In SwiftUI, List is a scrolling container that draws platform-style rows, and ForEach is a view (not a loop) that builds one child view for each element of a collection. You usually put a ForEach inside a List, give every element a stable ID through Identifiable or an id: key path, and attach onDelete and onMove to the ForEach. This page explains how SwiftUI uses those IDs, why id: \.self breaks with duplicate values, how to build dynamic rows and sections, how editing works, when ScrollView with LazyVStack is the better choice, and how to keep long lists fast.
Difficulty: Intermediate
Helpful to know first: how a SwiftUI view's body works, how @State stores data that changes, and Swift structs and arrays.
This article is about the SwiftUI views List and ForEach (capital F). If you wanted the forEach method that arrays have (lowercase f), read Swift forEach for the method itself, forEach vs for-in to choose between the method and a loop, forEach for side effects for when the method is the right tool, and for-in loops for plain loops.
How ForEach Builds Rows From Data
ForEach looks like a loop, but it is a struct that conforms to View. Its initializer stores two things: your collection and a closure that turns one element into a view. SwiftUI decides when to call that closure. Inside a List, it reads the ID of every element up front, but it builds row views only for the rows that are about to appear on screen.
The collection must be a RandomAccessCollection (an array, a range, an array slice), and every element needs an ID that is Hashable. Here is the smallest useful version:
import SwiftUI
struct Fruit: Identifiable {
let id: Int
let name: String
}
struct FruitListView: View {
let fruits = [
Fruit(id: 1, name: "Apple"),
Fruit(id: 2, name: "Banana"),
Fruit(id: 3, name: "Cherry")
]
var body: some View {
List {
ForEach(fruits) { fruit in
Text(fruit.name)
}
}
}
}The two views split the work. List gives you scrolling, separators, row insets, selection and swipe actions. ForEach gives you one Text per fruit, and the IDs 1, 2 and 3 tell SwiftUI which row is which when the array changes later.
When a list shows nothing but data rows, you can pass the data to List directly:
List(fruits) { fruit in
Text(fruit.name)
}This is a shortcut for a List that contains one ForEach. Use the long form when you need onDelete or onMove, sections, or fixed rows mixed with data rows, because those features belong to ForEach, not to List.
Because SwiftUI may call the row closure in any order, more than once, or not at all for rows that never scroll into view, the closure must only describe a view. Counting, logging or changing state inside it is unreliable.
How SwiftUI Identifies Each Row
Identity is how SwiftUI matches a row in the old version of your data to a row in the new version. If an element keeps its ID, SwiftUI updates that row in place: the row keeps its @State, and a reorder animates as a move. If the ID changes, SwiftUI removes the old row and inserts a new one, so the row's state resets and the change animates as a removal plus an insertion. Every rule below follows from this.
Identifiable for model data
Conform your model to Identifiable by giving it an id property. The best ID comes from the data itself, such as a database key or a server ID. A UUID also works, as long as it is created once, when the value is created, and then stored.
struct Contact: Identifiable {
let id: Int // the primary key from your database
var name: String
var email: String
}
let contact = Contact(id: 42, name: "Maya", email: "[email protected]")
print(contact.id, contact.name)
// Output: 42 Maya42 Maya
Classes get id for free: when a class conforms to Identifiable without declaring id, Swift uses ObjectIdentifier(self), so two different instances always have different IDs even if their properties are equal.
The id: parameter when a field is already unique
If a type already has a unique, stable field, point ForEach at it with a key path instead of adding Identifiable:
import SwiftUI
struct Country {
let isoCode: String
let name: String
}
struct CountryListView: View {
let countries = [
Country(isoCode: "JP", name: "Japan"),
Country(isoCode: "KE", name: "Kenya"),
Country(isoCode: "PE", name: "Peru")
]
var body: some View {
List {
ForEach(countries, id: \.isoCode) { country in
Text(country.name)
}
}
}
}Country codes are unique and never change for a country, which is exactly what an ID needs.
id: \.self and why it breaks with duplicates
id: \.self makes each element its own ID. It is fine for values that are unique and never edited, such as the names of the sections in a settings screen. It causes two kinds of trouble:
- Duplicates share an ID. If the array contains "Alex" twice, SwiftUI cannot tell the two rows apart. It logs a warning at run time, and rows can show the wrong content, animate strangely, or be deleted in the wrong place.
- Editing a value changes its ID. With a struct such as a to-do item, ticking it done makes it a different value, so SwiftUI treats the row as removed and a new row as inserted.
Hashing the whole value also costs more than reading an Int or UUID property, which matters in long lists.
Editing elements with ForEach($items)
Pass a binding to the array, $todos, and the closure receives a binding to each element. You can then edit elements directly without using indices:
import SwiftUI
struct Todo: Identifiable {
let id: Int
var title: String
var isDone: Bool
}
struct TodoListView: View {
@State private var todos = [
Todo(id: 1, title: "Book flights", isDone: false),
Todo(id: 2, title: "Renew passport", isDone: true)
]
var body: some View {
List {
ForEach($todos) { $todo in
Toggle(todo.title, isOn: $todo.isDone)
}
}
}
}Inside the closure, todo is the current value and $todo is its binding. The toggle writes straight back into the @State array, and the ID stays the same because id is a separate field. For more on where list data should live, see SwiftUI state management.
Building Real Lists: Dynamic Rows, Sections, Delete and Move
Adding rows at run time
Keep the array in @State (or in an observable model) and change it. SwiftUI compares the old and new IDs and inserts only the new row:
import SwiftUI
struct Note: Identifiable {
let id = UUID()
var text: String
}
struct NoteRow: View {
let note: Note
var body: some View {
Label(note.text, systemImage: "note.text")
}
}
struct NotesView: View {
@State private var notes = [Note(text: "Call the bank")]
var body: some View {
VStack {
List {
ForEach(notes) { note in
NoteRow(note: note)
}
}
Button("Add note") {
withAnimation {
notes.append(Note(text: "Note \(notes.count + 1)"))
}
}
}
}
}Here let id = UUID() is safe: each note gets its UUID once, when it is created, and the value is stored in @State. The row layout lives in its own NoteRow view, which keeps body short.
Grouping rows into sections
A Section inside a List adds a header and groups rows. For data-driven sections, nest one ForEach for the sections and another for the rows:
import SwiftUI
struct Expense: Identifiable {
let id: Int
let title: String
let category: String
let amount: Double
}
struct ExpensesView: View {
let expenses = [
Expense(id: 1, title: "Train ticket", category: "Travel", amount: 42),
Expense(id: 2, title: "Lunch", category: "Food", amount: 14.5),
Expense(id: 3, title: "Hotel", category: "Travel", amount: 310),
Expense(id: 4, title: "Coffee", category: "Food", amount: 3.2)
]
var categories: [String] {
Set(expenses.map(\.category)).sorted()
}
var body: some View {
List {
ForEach(categories, id: \.self) { category in
Section(category) {
ForEach(expenses.filter { $0.category == category }) { expense in
HStack {
Text(expense.title)
Spacer()
Text(expense.amount, format: .currency(code: "EUR"))
}
}
}
}
}
}
}This is a correct use of id: \.self: the category names come from a Set, so they are unique. Sorting matters too. A Set or a dictionary built with Dictionary(grouping:by:) has no fixed order, and its order can differ between launches, so unsorted sections can jump around.
Swipe to delete and drag to reorder
Attach onDelete and onMove to the ForEach. SwiftUI passes positions (offsets) in the array you gave that ForEach, and SwiftUI adds matching helpers to arrays: remove(atOffsets:) and move(fromOffsets:toOffset:).
import SwiftUI
struct Song: Identifiable {
let id: Int
let title: String
}
struct PlaylistView: View {
@State private var songs = [
Song(id: 1, title: "Intro"),
Song(id: 2, title: "Night Drive"),
Song(id: 3, title: "Rainfall")
]
var body: some View {
NavigationStack {
List {
ForEach(songs) { song in
Text(song.title)
}
.onDelete { offsets in
songs.remove(atOffsets: offsets)
}
.onMove { source, destination in
songs.move(fromOffsets: source, toOffset: destination)
}
}
.navigationTitle("Playlist")
.toolbar {
EditButton()
}
}
}
}On iOS, onDelete alone turns on swipe-to-delete, and the EditButton switches the list into edit mode with delete buttons and drag handles. EditButton exists on iOS and iPadOS but not on macOS, where the compiler reports 'EditButton' is unavailable in macOS. For custom swipe buttons such as "Archive" or "Pin", use the swipeActions modifier on the row instead.
The offsets only match your array when the ForEach shows that exact array. If it shows a filtered or sorted copy, convert the offsets to IDs first. The Find the Bug section below shows what happens when you forget.
What Happens When the Data Changes
Each time the array changes, SwiftUI compares the list of IDs before and after. IDs that disappeared become removals, new IDs become insertions, and IDs that changed position become moves. Rows whose ID stayed the same keep their view state, such as a @State flag that expands a row.
That is why the ID must not depend on anything the user can edit. A row identified by its title loses its state when the user renames it, and a row identified by a fresh UUID() on every update loses it constantly.
The type of the collection matters as well. ForEach needs random access, so a Set or a dictionary does not work directly:
import SwiftUI
struct TagsView: View {
let tags: Set<String> = ["swift", "ios", "ui"]
var body: some View {
List {
ForEach(tags, id: \.self) { tag in
Text(tag)
}
}
}
}The compiler rejects it with generic struct 'ForEach' requires that 'Set<String>' conform to 'RandomAccessCollection'. Pass tags.sorted() instead, which is an array and also gives the rows a stable order. For a dictionary, iterate over dictionary.keys.sorted() or over the sorted key-value pairs.
Keeping Long Lists Fast
List is built on the platform's own list views (UIKit on iOS, AppKit on macOS) and only creates views for rows near the screen, so thousands of rows are normal. What slows a list down is usually the work you give it per row or per update:
- Cheap, stable IDs. A List reads every ID, even for rows that are off screen. An Int or UUID property is cheap. id: \.self on a large struct hashes the whole value for every element.
- One view per element. If the row closure sometimes returns nothing (an if around the row), SwiftUI cannot know how many rows there are without building them. Filter the data before it reaches ForEach.
- Heavy work outside body. Sorting, grouping and filtering in a computed property run again every time body runs. For large data, compute the result when the data changes and store it.
- Row views as separate structs. A small row view with only the inputs it needs lets SwiftUI skip rows whose inputs did not change.
Here is the filtering rule in code. Both versions show the same rows, but the second one gives the list exactly one view per element:
import SwiftUI
struct Order: Identifiable {
let id: Int
let customer: String
let isOpen: Bool
}
struct OpenOrdersView: View {
let orders: [Order]
var body: some View {
List {
// Slower: SwiftUI must build every row to find out which ones exist
// ForEach(orders) { order in
// if order.isOpen { Text(order.customer) }
// }
// Better: one row per element, filtered before ForEach
ForEach(orders.filter(\.isOpen)) { order in
Text(order.customer)
}
}
}
}List or ScrollView With LazyVStack?
ForEach works inside any container, so the real choice is the container around it:
| List | ScrollView + LazyVStack | ScrollView + VStack | |
|---|---|---|---|
| When rows are created | Only near the screen | The first time each row scrolls into view | All at once, when the view appears |
| Look | Platform rows, separators, insets, list styles | None: you style every row | None: you style every row |
| Swipe actions, onDelete, onMove, edit mode | Yes | No | No |
| Selection | List(selection:) | Build it yourself | Build it yourself |
| Good for | Data lists, settings, inboxes, long lists | Custom feeds and cards | A handful of rows |
A card feed with no separators and no editing is a typical LazyVStack job:
import SwiftUI
struct Photo: Identifiable {
let id: Int
let caption: String
}
struct FeedView: View {
let photos = (1...500).map { Photo(id: $0, caption: "Photo \($0)") }
var body: some View {
ScrollView {
LazyVStack(spacing: 12) {
ForEach(photos) { photo in
Text(photo.caption)
.frame(maxWidth: .infinity, minHeight: 120)
.background(.quaternary, in: RoundedRectangle(cornerRadius: 12))
}
}
.padding()
}
}
}A plain VStack here would create all 500 rows as soon as the screen appears. For rows in columns, use the lazy grids covered in LazyVGrid and LazyHGrid.
Predict the Output
Each snippet tests a behaviour that trips people up when they write onMove handlers or choose an ID.
Where does the moved element land?
import SwiftUI
var steps = ["Wash", "Cut", "Cook", "Serve"]
steps.move(fromOffsets: IndexSet(integer: 0), toOffset: 2)
print(steps)What does this print?
Show answer
It prints ["Cut", "Wash", "Cook", "Serve"], not ["Cut", "Cook", "Wash", "Serve"].
The destination is a position in the array as it was before the move: "insert before the element that is at offset 2 now", which is "Cook". Once "Wash" is taken out, that slot is index 1. onMove passes destinations the same way, so pass them straight to move(fromOffsets:toOffset:) and do not subtract 1 yourself. To move an element to the end, the destination is steps.count.
Does the ID survive an edit?
struct Todo: Hashable {
var title: String
var isDone: Bool
}
var todo = Todo(title: "Buy milk", isDone: false)
let idBefore = todo // with id: \.self, the whole value is the ID
todo.isDone = true
print(idBefore == todo)What does this print?
Show answer
It prints false. With ForEach(todos, id: \.self), ticking an item done gives it a new ID. SwiftUI sees one row removed and another inserted instead of an update, so any @State inside that row resets and the change animates as if the row were new. Give the type a separate id property that never changes.
Common Mistakes With List and ForEach
Writing a for loop inside List
People coming from UIKit or from plain Swift try to loop over the data inside the view body.
Problem: body is built by the ViewBuilder result builder, which does not support for loops, so the code does not compile: closure containing control flow statement cannot be used with result builder 'ViewBuilder'.
import SwiftUI
struct NamesView: View {
let names = ["Ana", "Ben", "Cleo"]
var body: some View {
List {
for name in names {
Text(name)
}
}
}
}Fix: Use the ForEach view, which is what the result builder expects for repeated content.
import SwiftUI
struct NamesView: View {
let names = ["Ana", "Ben", "Cleo"]
var body: some View {
List {
ForEach(names, id: \.self) { name in
Text(name)
}
}
}
}This works because ForEach is itself a view; see result builders in SwiftUI for why if is allowed in a body but for is not.
Passing a type that has no ID
The short ForEach(items) form only works when the element type is Identifiable.
Problem: Product has no id, so the compiler stops with referencing initializer 'init(_:content:)' on 'ForEach' requires that 'Product' conform to 'Identifiable'.
import SwiftUI
struct Product {
let name: String
let price: Double
}
struct ProductsView: View {
let products = [
Product(name: "Keyboard", price: 49),
Product(name: "Mouse", price: 25)
]
var body: some View {
List {
ForEach(products) { product in
Text(product.name)
}
}
}
}Fix: Add Identifiable with a stable id, or pass id: with a key path to a unique field.
import SwiftUI
struct Product: Identifiable {
let id: String // the SKU
let name: String
let price: Double
}
struct ProductsView: View {
let products = [
Product(id: "KB-01", name: "Keyboard", price: 49),
Product(id: "MS-02", name: "Mouse", price: 25)
]
var body: some View {
List {
ForEach(products) { product in
Text(product.name)
}
}
}
}The corrected version works because every product now carries an ID that SwiftUI can track across updates.
Using id: \.self with values that repeat
Names, titles and prices often repeat, even when they look unique in test data.
Problem: Two rows share the ID "Alex". The code compiles, but at run time SwiftUI logs ForEach<Array<String>, String, Text>: the ID Alex occurs multiple times within the collection, this will give undefined results! and rows can show or delete the wrong content.
import SwiftUI
struct TeamView: View {
let names = ["Alex", "Sam", "Alex"]
var body: some View {
List {
ForEach(names, id: \.self) { name in
Text(name)
}
}
}
}Fix: Model each person with an ID of their own.
import SwiftUI
struct Member: Identifiable {
let id: Int
let name: String
}
struct TeamView: View {
let members = [
Member(id: 1, name: "Alex"),
Member(id: 2, name: "Sam"),
Member(id: 3, name: "Alex")
]
var body: some View {
List {
ForEach(members) { member in
Text(member.name)
}
}
}
}The corrected version works because the two Alexes are now two different IDs, so SwiftUI keeps their rows apart.
Creating new IDs on every update
A model with let id = UUID() is fine when values are stored. It breaks when the values are rebuilt from other data each time body runs.
Problem: rows is a computed property, so every update creates new Row values with new UUIDs. To SwiftUI, every row is new every time: row state resets, animations replace rows instead of updating them, and the list does more work than it needs to.
import SwiftUI
struct Row: Identifiable {
let id = UUID()
let title: String
}
struct MenuView: View {
let titles = ["Home", "Search", "Profile"]
var rows: [Row] { titles.map { Row(title: $0) } }
var body: some View {
List(rows) { row in
Text(row.title)
}
}
}Fix: Derive the ID from the data, so the same title always produces the same ID.
import SwiftUI
struct Row: Identifiable {
let title: String
var id: String { title }
}
struct MenuView: View {
let titles = ["Home", "Search", "Profile"]
var rows: [Row] { titles.map { Row(title: $0) } }
var body: some View {
List(rows) { row in
Text(row.title)
}
}
}The corrected version works because rebuilding rows now produces the same IDs, so SwiftUI sees no change and leaves the rows alone.
Attaching onDelete to the List
Swipe-to-delete feels like a feature of the list, so people put the modifier on List.
Problem: onDelete is defined for dynamic content such as ForEach, not for List, so the compiler reports value of type 'List<Never, ForEach<[Fruit], UUID, Text>>' has no member 'onDelete'.
import SwiftUI
struct Fruit: Identifiable {
let id = UUID()
var name: String
}
struct FruitsView: View {
@State private var fruits = [Fruit(name: "Apple"), Fruit(name: "Pear")]
var body: some View {
List {
ForEach(fruits) { fruit in
Text(fruit.name)
}
}
.onDelete { offsets in
fruits.remove(atOffsets: offsets)
}
}
}Fix: Move the modifier onto the ForEach, inside the List.
import SwiftUI
struct Fruit: Identifiable {
let id = UUID()
var name: String
}
struct FruitsView: View {
@State private var fruits = [Fruit(name: "Apple"), Fruit(name: "Pear")]
var body: some View {
List {
ForEach(fruits) { fruit in
Text(fruit.name)
}
.onDelete { offsets in
fruits.remove(atOffsets: offsets)
}
}
}
}The corrected version works because the offsets refer to the rows of that ForEach, which is the array you remove from.
Looping over a range of indices that changes
ForEach(0..<count) without an id: is meant for a fixed number of views, such as five rating stars.
Problem: The range depends on data that changes, so the compiler warns non-constant range: argument must be an integer literal. This form reads the range only once, when the view first appears, and identifies rows by position, so it does not follow insertions and deletions.
import SwiftUI
struct ScoresView: View {
@State private var scores = [12, 40, 7]
var body: some View {
List {
ForEach(0..<scores.count) { index in
Text("Score: \(scores[index])")
}
.onDelete { offsets in
scores.remove(atOffsets: offsets)
}
}
}
}Fix: Give each score an identity and iterate over the elements, not the indices.
import SwiftUI
struct Score: Identifiable {
let id = UUID()
let points: Int
}
struct ScoresView: View {
@State private var scores = [Score(points: 12), Score(points: 40), Score(points: 7)]
var body: some View {
List {
ForEach(scores) { score in
Text("Score: \(score.points)")
}
.onDelete { offsets in
scores.remove(atOffsets: offsets)
}
}
}
}The corrected version works because each row is tied to a score, not to a position that shifts when rows are deleted.
Find the Bug
This inbox shows only unread messages and lets the user swipe to delete. It compiles and looks right. What goes wrong when the user swipes away "Meeting"?
import SwiftUI
struct Message: Identifiable {
let id: Int
var subject: String
var isRead = false
}
struct InboxView: View {
@State private var messages = [Message(id: 1, subject: "Invoice", isRead: true),
Message(id: 2, subject: "Meeting"),
Message(id: 3, subject: "Lunch?")]
var unread: [Message] { messages.filter { !$0.isRead } }
var body: some View {
List {
ForEach(unread) { Text($0.subject) }
.onDelete { messages.remove(atOffsets: $0) }
}
}
}Show answer
The offsets describe positions in unread, the array the ForEach shows, but the code removes from messages. "Meeting" is offset 0 in unread, and offset 0 in messages is "Invoice". So the hidden, read message is deleted, and "Meeting" stays on screen. With other data the same mistake deletes a different visible row from the one the user swiped.
Convert the offsets to IDs using the array that is on screen, then remove by ID:
import SwiftUI
struct Message: Identifiable {
let id: Int
var subject: String
var isRead = false
}
struct InboxView: View {
@State private var messages = [Message(id: 1, subject: "Invoice", isRead: true),
Message(id: 2, subject: "Meeting"),
Message(id: 3, subject: "Lunch?")]
var unread: [Message] { messages.filter { !$0.isRead } }
var body: some View {
List {
ForEach(unread) { Text($0.subject) }
.onDelete { offsets in
let ids = Set(offsets.map { unread[$0].id })
messages.removeAll { ids.contains($0.id) }
}
}
}
}When to Use List, ForEach, or Something Else
- Use List with ForEach for rows of data that the user scrolls, selects, swipes, deletes or reorders.
- Use ForEach inside a LazyVStack or a lazy grid for a custom-looking feed without list behaviour.
- Use ForEach inside an HStack or VStack for a few repeated views, such as rating stars or tag chips.
- Use the forEach method or a for-in loop for code that runs, such as saving or printing each element. They do not produce views, so they cannot build the rows in body.
Interview Questions About List and ForEach
Why does ForEach need an ID for every element?
SwiftUI compares the IDs before and after each change to decide which rows to insert, remove, move or update. The ID gives each row an explicit identity, so its state and animations follow the data instead of the position.
What is the difference between List(items) and List { ForEach(items) }?
They show the same rows. The ForEach form also allows onDelete, onMove, sections, and static rows mixed with data rows, because those features are attached to ForEach.
Try It Yourself
Build a grocery list with two sections.
- Create a GroceryItem model with a stable ID, a name, and an inCart flag.
- Add a text field at the top that adds a new item when the user presses Return, and ignores empty names.
- Show two sections, "To buy" and "In cart", each with its item count in the header.
- Tapping an item moves it to the other section.
- Swiping an item deletes that exact item, in either section.
Expected output: A list with an "Add" field, a "To buy (2)" section with Eggs and Rice, and an "In cart (1)" section with Tea. Tapping Rice moves it to "In cart (2)", and swiping Eggs removes only Eggs.
Hint: Give each section its own filtered array, and delete by ID as in the Find the Bug fix, because each section's offsets refer to its own filtered array.
Show solution
import SwiftUI
struct GroceryItem: Identifiable {
let id = UUID()
var name: String
var inCart = false
}
struct GroceryListView: View {
@State private var items = [
GroceryItem(name: "Eggs"),
GroceryItem(name: "Rice"),
GroceryItem(name: "Tea", inCart: true)
]
@State private var newName = ""
var toBuy: [GroceryItem] { items.filter { !$0.inCart } }
var inCart: [GroceryItem] { items.filter(\.inCart) }
var body: some View {
List {
Section("Add") {
TextField("New item", text: $newName)
.onSubmit(addItem)
}
Section("To buy (\(toBuy.count))") {
ForEach(toBuy) { item in
Button(item.name) { toggle(item) }
}
.onDelete { offsets in delete(offsets, from: toBuy) }
}
Section("In cart (\(inCart.count))") {
ForEach(inCart) { item in
Button(item.name) { toggle(item) }
.foregroundStyle(.secondary)
}
.onDelete { offsets in delete(offsets, from: inCart) }
}
}
}
func addItem() {
let name = newName.trimmingCharacters(in: .whitespaces)
guard !name.isEmpty else { return }
items.append(GroceryItem(name: name))
newName = ""
}
func toggle(_ item: GroceryItem) {
guard let index = items.firstIndex(where: { $0.id == item.id }) else { return }
items[index].inCart.toggle()
}
func delete(_ offsets: IndexSet, from shown: [GroceryItem]) {
let ids = Set(offsets.map { shown[$0].id })
items.removeAll { ids.contains($0.id) }
}
}Summary
- List is the scrolling, platform-styled container; ForEach is a view that turns each element of a random-access collection into a row. Neither is the forEach method.
- Every element needs a stable, unique ID: Identifiable, an id: key path to a unique field, or id: \.self only for unique values that never change.
- Duplicate IDs give "undefined results", and IDs that change on edit or on every update reset row state and break animations.
- Attach onDelete and onMove to ForEach; their offsets refer to the array that ForEach shows, so delete by ID when it shows a filtered copy.
- Use List for editable data lists and long lists, LazyVStack for custom feeds, and keep one cheap view per element.
Next, make the rows open a detail screen with NavigationLink, covered in SwiftUI navigation with NavigationStack.