Lists and Navigation

Article · 2:00

List for dynamic data, and NavigationStack, sheets and alerts for moving between screens.

List is the table view of SwiftUI, and it is lazy - rows are built as they scroll into view, so a list of ten thousand items costs about what a list of twenty costs. To build rows from data, the data must be identifiable: either conform your model to Identifiable with an id property, or tell the list which property to use with id:.

Multi-screen flow lives in NavigationStack. Wrap the root, give rows a NavigationLink, and declare what each destination type looks like with navigationDestination(for:). Driving navigation by type rather than by wiring each link to a specific view is what makes the pattern scale: a deep link, a notification tap and a row tap all end up appending a value to the same path.

Not every screen belongs on the stack. A sheet slides up for a self-contained task the reader will finish and dismiss - adding an item, editing a setting. An alert is for a short confirmation or an error, and should have a title that says what happened rather than the word "Error".

import SwiftUI

struct Task: Identifiable, Hashable {
    let id = UUID()
    var title: String
    var done = false
}

struct TaskList: View {
    @State private var tasks = [
        Task(title: "Install Xcode"),
        Task(title: "Write a Playground"),
        Task(title: "Ship something"),
    ]
    @State private var showingAdd = false
    @State private var errorMessage: String?

    var body: some View {
        NavigationStack {
            List {
                // Rows are built lazily as they scroll in.
                ForEach(tasks) { task in
                    NavigationLink(value: task) {
                        Label(task.title, systemImage: task.done ? "checkmark.circle.fill" : "circle")
                    }
                }
                .onDelete { tasks.remove(atOffsets: $0) }
            }
            .navigationTitle("Tasks")
            // Navigation by TYPE: anything appending a Task lands here.
            .navigationDestination(for: Task.self) { task in
                Text(task.title).font(.largeTitle)
            }
            .toolbar {
                Button("Add", systemImage: "plus") { showingAdd = true }
            }
            // A sheet for a self-contained task.
            .sheet(isPresented: $showingAdd) {
                Text("A form would go here").presentationDetents([.medium])
            }
            // An alert whose title says what happened.
            .alert("Could not save your task",
                   isPresented: .constant(errorMessage != nil),
                   presenting: errorMessage) { _ in
                Button("OK") { errorMessage = nil }
            } message: { Text($0) }
        }
    }
}

#Preview { TaskList() }