SyntaxStudy
Sign Up
Swift Navigation and Data Flow
Swift Beginner 1 min read

Navigation and Data Flow

NavigationStack (iOS 16+) replaces NavigationView and supports programmatic navigation via a path binding. NavigationLink pushes a destination view, and navigationDestination(for:) registers destinations for value types. Shared state across views uses @EnvironmentObject (injected into the environment) or @Environment for system values. The Observation framework (iOS 17+) with @Observable replaces ObservableObject. Sheets, fullScreenCover, popovers, and alerts are presented with boolean or optional item bindings.
Example
import SwiftUI

@Observable
class AppState {
    var currentUser: String = "Alice"
    var isLoggedIn: Bool = true
}

struct RootView: View {
    @State private var appState = AppState()
    @State private var path = NavigationPath()

    var body: some View {
        NavigationStack(path: $path) {
            HomeView()
                .navigationDestination(for: Int.self) { id in
                    DetailView(id: id)
                }
                .navigationDestination(for: String.self) { name in
                    ProfileView(name: name)
                }
        }
        .environment(appState)
    }
}

struct HomeView: View {
    @Environment(AppState.self) private var appState
    @State private var showSheet = false

    var body: some View {
        List(1...5, id: \.self) { id in
            NavigationLink("Item \(id)", value: id)
        }
        .navigationTitle("Home")
        .toolbar {
            Button("Profile") { showSheet = true }
        }
        .sheet(isPresented: $showSheet) {
            ProfileView(name: appState.currentUser)
                .presentationDetents([.medium, .large])
        }
    }
}

struct DetailView: View {
    let id: Int
    var body: some View {
        Text("Detail for item \(id)").navigationTitle("Item \(id)")
    }
}

struct ProfileView: View {
    let name: String
    var body: some View {
        Text("Profile: \(name)").font(.largeTitle)
    }
}