# SwiftUI Architecture in 2026: Observation, Navigation and Liquid Glass

> SwiftUI architecture for iOS 26: Observation, state ownership, routing, Swift 6.2 concurrency, SwiftData, Swift Testing, profiling and Liquid Glass, with a full feature.

Source: https://www.derar.dev/blog/swiftui-architecture-observation-liquid-glass-ios-26-guide · Published 2026-11-11 · Updated 2026-11-14 · By Derar Sattouf

SwiftUI is no longer the new thing you adopt cautiously. By the iOS 26 generation it is the default way to build Apple-platform interfaces, and the questions have changed. Nobody asks whether SwiftUI can do a list any more. People ask how to structure state so views stay cheap, how to route without a tangle of booleans, where an actor boundary belongs, whether SwiftData is ready for their data, and how to adopt the Liquid Glass design language without making the app look like a tech demo.

The architecture here is opinionated and simple. Use `@Observable` (the Observation framework) for models. It tracks property reads per view, so views re-render only when a property they actually read changes, and you can drop `ObservableObject`, `@Published`, `@StateObject` and `@ObservedObject` in new code. Own state in exactly one place: `@State` for view-local state and for owning an `@Observable` model, `@Bindable` to create bindings to a model passed in, `@Environment` for shared dependencies, plain properties for read-only inputs.

Route with `NavigationStack` and a typed path. Model navigation as data (an enum per destination), keep the path in a small router object, and let deep links append to the path. For concurrency, keep UI-facing models on the main actor, isolate shared mutable state in actors, and prefer structured concurrency. With Swift 6.2 and Xcode 26, new projects can default to main-actor isolation, which removes a lot of noise; use `@concurrent` for work that must run off the main actor.

Pick the simplest architecture that works. For most apps, plain SwiftUI plus `@Observable` models plus a small service layer beats a heavy framework. Reach for The Composable Architecture (TCA) when you want strict, testable reducers and a team that already knows it. SwiftData is good for local app data, while Core Data is still right for complex migrations, shared stores and very large datasets. Hide either behind a protocol so views never import persistence details.

Test logic with Swift Testing, test UI sparingly with XCUITest, and measure with Instruments (the SwiftUI template and Time Profiler), not guesses. For Liquid Glass, recompile first, then remove custom chrome. Use system components, apply `glassEffect` only to a few custom floating controls, never put glass on glass, and test accessibility settings.

Apple changes APIs every June and point-releases through the year. The code below targets Swift 6.2 and the iOS 26 SDK era, and where an API is new or its availability has moved, the text says so. When in doubt, check the live documentation and the release notes of the Xcode you are using before relying on a signature. Before you apply any of this (or ask an AI agent to), confirm the deployment target (Observation needs iOS 17), the Swift language mode and default isolation settings, whether the project uses SwiftData or Core Data, and which iOS 26 APIs are available on your minimum OS.

## The mental model: views are functions of state

SwiftUI views are cheap value types that describe UI for a given state. SwiftUI calls `body` when something the view read has changed, diffs the result, and updates the underlying render tree. Three consequences drive every architecture decision:

1. **`body` must be fast and free of side effects.** It can run often. No networking, no sorting 10,000 items, no creating formatters or model objects inline.
2. **Identity matters more than the view struct.** A view's identity (position in the hierarchy, explicit `id`, or `.id()` modifier) decides whether SwiftUI keeps its state or recreates it.
3. **State has an owner.** SwiftUI keeps the storage for `@State` outside the struct so it survives body re-evaluation. If you create a model in `body` or in an initialiser that runs repeatedly, you are creating a new model each time.

The architecture below is a direct application of those three facts.

```text
┌─────────────────────────────────────────────────────────┐
│ View layer (SwiftUI)                                    │
│   Views read @Observable models; send intents as method │
│   calls; never touch persistence or networking directly │
└───────────────┬─────────────────────────────────────────┘
                │ owns / receives
┌───────────────▼─────────────────────────────────────────┐
│ Model layer (@Observable, @MainActor by default)        │
│   View state + intent methods; orchestrates services    │
└───────────────┬─────────────────────────────────────────┘
                │ protocols injected via init / Environment
┌───────────────▼─────────────────────────────────────────┐
│ Service layer (actors / Sendable structs)               │
│   API client, repositories, SwiftData/Core Data wrapper │
└─────────────────────────────────────────────────────────┘
```

## Observation: `@Observable` versus `ObservableObject`

### What changed

`ObservableObject` publishes a single `objectWillChange` signal. Any view that holds the object as `@ObservedObject` or `@StateObject` re-evaluates when **any** `@Published` property changes, even one it never reads. `@Observable` (the Observation framework, introduced with iOS 17 and available in the iOS 26 SDK) works differently: the macro rewrites stored properties so that reads are recorded per access, and SwiftUI re-renders a view only when a property that view actually read in its `body` changes.

| Aspect | `ObservableObject` | `@Observable` |
|---|---|---|
| Declaration | `class Model: ObservableObject` with `@Published` | `@Observable class Model`, plain stored properties |
| Change granularity | Whole object | Per property that was read |
| Owning in a view | `@StateObject` | `@State` |
| Receiving in a view | `@ObservedObject` | Plain property, or `@Bindable` if you need bindings |
| Shared environment | `@EnvironmentObject` | `@Environment(Type.self)` |
| Optional or collection of models | Awkward | Works naturally |
| Excluding a property from tracking | Not published | `@ObservationIgnored` |
| Minimum OS | iOS 13 | iOS 17 |

If your deployment target is iOS 17 or later, there is no reason to write `ObservableObject` in new code. If you support older iOS, the Observation backport is not available; keep `ObservableObject` for those targets or raise the minimum. Most apps in late 2026 can safely target iOS 17 or 18 as a floor, but check your own analytics.

### A model with `@Observable`

```swift
import Observation

@MainActor
@Observable
final class ProfileModel {
    var displayName = ""
    var bio = ""
    private(set) var isSaving = false
    private(set) var errorMessage: String?

    @ObservationIgnored
    private let service: ProfileService

    init(service: ProfileService) {
        self.service = service
    }

    func load() async {
        do {
            let profile = try await service.fetch()
            displayName = profile.displayName
            bio = profile.bio
        } catch {
            errorMessage = error.localizedDescription
        }
    }

    func save() async {
        isSaving = true
        defer { isSaving = false }
        do {
            try await service.update(displayName: displayName, bio: bio)
            errorMessage = nil
        } catch {
            errorMessage = error.localizedDescription
        }
    }
}
```

Mark the class `@MainActor` explicitly unless your project uses main-actor default isolation (covered in the Swift 6.2 concurrency changes below). View-facing state mutated from background tasks is the most common source of data-race warnings and visual glitches.

### Pitfalls

- **Creating the model in `body`.** `ProfileModel(...)` inside `body` makes a new model on every evaluation. Own it with `@State` instead.
- **Heavy `init` work in a `@State` initial value.** The initial value expression runs each time the view struct is created, even though only the first is kept. Keep model initialisers cheap and push work into `load()`.
- **Computed properties that read many stored properties.** They register dependencies on all of them, which is correct but can cause wider invalidation than expected. Keep derived values small.
- **Mixing both systems on one model.** Do not combine `@Observable` and `ObservableObject` on a type.
- **Expecting Combine-style streams.** `@Observable` is for view updates. For an async stream of changes outside views, Swift 6.2 added the `Observations` type for observing changes as an async sequence; check availability and the signature in the current documentation before using it.

## State ownership: the rules

Most SwiftUI bugs are ownership bugs. Use this table as a decision procedure.

| Situation | Use |
|---|---|
| Simple value local to the view (toggle, text field, selected tab) | `@State private var` |
| This view creates and owns an `@Observable` model | `@State private var model = Model(...)` |
| A parent passes a model and the child only reads it | Plain `let model: Model` or `var model: Model` |
| A parent passes a model and the child needs `$` bindings into it | `@Bindable var model: Model` |
| A value the child can modify and the parent owns (value type) | `@Binding var value: T` |
| A dependency shared across a subtree (router, service container, theme) | `@Environment(Type.self) private var x` |
| System values (dismiss, color scheme, size class, locale) | `@Environment(\.keyPath)` |
| Persisted small values | `@AppStorage`, or `@SceneStorage` for per-scene UI restoration |
| Data fetched from SwiftData | `@Query` in the view, or via a model that owns a `ModelContext` |

### `@State` owning a model

```swift
struct ProfileScreen: View {
    @State private var model: ProfileModel

    init(service: ProfileService) {
        _model = State(initialValue: ProfileModel(service: service))
    }

    var body: some View {
        ProfileForm(model: model)
            .task { await model.load() }
    }
}
```

The `State(initialValue:)` pattern keeps the model created once for the lifetime of the view's identity. The initialiser closure runs again if the parent re-creates the struct, but SwiftUI keeps the original state and discards the new one. This is why model initialisers must be cheap.

### `@Bindable` for bindings into a model

```swift
struct ProfileForm: View {
    @Bindable var model: ProfileModel

    var body: some View {
        Form {
            TextField("Display name", text: $model.displayName)
            TextField("Bio", text: $model.bio, axis: .vertical)
                .lineLimit(3...6)

            Section {
                Button("Save") { Task { await model.save() } }
                    .disabled(model.isSaving)
            }

            if let error = model.errorMessage {
                Text(error).foregroundStyle(.red)
            }
        }
        .navigationTitle("Profile")
    }
}
```

`@Bindable` does not own the model; it only enables `$model.property` syntax. Use it in the child, and keep `@State` in the owner.

### `@Environment` for dependencies

Observable objects can be placed in the environment by type and read by type. This removes the old `@EnvironmentObject` crash when an object was missing, although an `@Environment(Type.self)` read of a missing non-optional object will also trap at runtime; inject at the root and consider optionals for tests.

```swift
@main
struct ShopApp: App {
    @State private var router = Router()
    @State private var services = ServiceContainer.live()

    var body: some Scene {
        WindowGroup {
            RootView()
                .environment(router)
                .environment(services)
        }
    }
}

struct RootView: View {
    @Environment(Router.self) private var router
    @Environment(ServiceContainer.self) private var services

    var body: some View { /* ... */ }
}
```

For a protocol-typed or value-typed dependency, define a custom `EnvironmentKey` and expose it through an extension on `EnvironmentValues`. Keep the default value a safe, inert implementation so previews work.

### Passing less

Pass the smallest thing a view needs. A row that displays a title and a favourite flag should take two values or a small struct, not the whole `Model`. Small inputs make views cheaper to compare, easier to preview, and unaffected by unrelated model changes.

## Navigation and routing

### Typed path routing

`NavigationStack` with `navigationDestination(for:)` and a bound path array gives you programmatic, testable, restorable navigation. Model destinations as an enum.

```swift
import SwiftUI

enum Route: Hashable {
    case productDetail(id: Product.ID)
    case cart
    case checkout(orderID: UUID)
    case settings
}

@MainActor
@Observable
final class Router {
    var path: [Route] = []

    func push(_ route: Route) { path.append(route) }
    func pop() { _ = path.popLast() }
    func popToRoot() { path.removeAll() }

    func handle(url: URL) {
        // Map https://example.com/products/42 or myapp://products/42
        let parts = url.pathComponents.filter { $0 != "/" }
        if parts.first == "products", let raw = parts.dropFirst().first, let id = Int(raw) {
            popToRoot()
            push(.productDetail(id: id))
        }
    }
}

struct RootView: View {
    @Environment(Router.self) private var router

    var body: some View {
        @Bindable var router = router
        NavigationStack(path: $router.path) {
            CatalogView()
                .navigationDestination(for: Route.self) { route in
                    switch route {
                    case .productDetail(let id): ProductDetailView(productID: id)
                    case .cart: CartView()
                    case .checkout(let orderID): CheckoutView(orderID: orderID)
                    case .settings: SettingsView()
                    }
                }
        }
        .onOpenURL { router.handle(url: $0) }
    }
}
```

The `@Bindable var router = router` line inside `body` is the idiomatic way to get a binding to a model that arrived through the environment.

### Heterogeneous paths and persistence

A `[Route]` array is easy to inspect and test, and it conforms to `Codable` if each case's payload does. That makes state restoration straightforward: encode the path into `@SceneStorage` and decode it at launch. If you need to mix unrelated types in one stack, use `NavigationPath`, but you lose the ability to read the typed elements back, which makes tests and analytics harder. Prefer the typed array unless you have a strong reason.

### Tabs, sheets and presentation

- Give each tab its own `NavigationStack` and its own router (or path) so that tab switching preserves per-tab history.
- Model sheets as state: `@State private var sheet: Sheet?` with `.sheet(item: $sheet)` and an `Identifiable` enum, rather than several booleans.
- Dismiss from a child with `@Environment(\.dismiss)` and avoid passing closures through four levels.

With the iOS 18 generation, the `Tab` type and `TabView` with `Tab` values are the modern tab API; on iOS 26 they integrate with the new floating tab bar behaviour (see the Liquid Glass section). Verify the current `Tab` initialisers, including the `role: .search` variant for a search tab, in the documentation for your SDK.

### Common navigation mistakes

- Putting `NavigationLink(destination:)` with eagerly constructed destinations inside lists; use value-based links so destinations are built lazily.
- Wrapping each screen in its own `NavigationStack`; use one stack per navigation context.
- Storing a path of reference-type models. Store identifiers and rebuild models in the destination.
- Forgetting that `navigationDestination` must be attached inside the stack, and registered once per type, not once per row.

## Swift concurrency for UI apps

### The four ideas you need

1. **`async`/`await`** is how you write sequential code that suspends instead of blocking.
2. **Actors** protect their mutable state: only one task runs on an actor at a time, and cross-actor calls are `await`ed.
3. **`@MainActor`** is the global actor for the main thread. UI types and view-facing models belong there.
4. **Structured concurrency** (`async let`, `TaskGroup`, `.task`) ties child work to a parent scope so cancellation and errors propagate.

### Use `.task`, not `onAppear { Task { } }`

The `.task` modifier starts async work when the view appears and cancels it when the view disappears or its `id` changes. It is the right default.

```swift
.task(id: query) {
    // Cancelled and restarted whenever 'query' changes.
    try? await Task.sleep(for: .milliseconds(300)) // debounce
    guard !Task.isCancelled else { return }
    await model.search(query)
}
```

Unstructured `Task { }` inside `onAppear` does not cancel on disappear and leaks work. If you must create a task to run from a button, store its handle if it can be superseded, and check `Task.isCancelled` in long operations.

### Swift 6.2 changes: approachable concurrency

Swift 6 turned data-race safety into compile-time errors under the Swift 6 language mode. That was powerful and noisy. Swift 6.2, shipped with Xcode 26, introduced "approachable concurrency":

- **Default actor isolation.** A build setting (and a Swift Package setting) lets a module default to `@MainActor` isolation. New Xcode 26 app projects have it enabled; existing projects opt in. Code that does not need concurrency stays single-threaded with no annotations.
- **`nonisolated` async functions run in the caller's isolation** by default under the new upcoming feature, instead of hopping to a global executor. This removes a family of surprising warnings. The feature flag is commonly called `NonisolatedNonsendingByDefault`; check the Swift evolution proposals for the current name and status.
- **`@concurrent`** explicitly marks an async function that must run off the caller's actor, for CPU-heavy or blocking work.

```swift
// With default actor isolation = MainActor, this whole type is main-actor isolated.
@Observable
final class FeedModel {
    var items: [FeedItem] = []

    func refresh() async {
        let data = await fetchAndDecode() // runs off the main actor
        items = data                      // back on the main actor
    }
}

@concurrent
func fetchAndDecode() async -> [FeedItem] {
    // Heavy decoding or parsing that should not block the UI.
    []
}
```

Practical advice: turn on default main-actor isolation for the **app target**, and keep your **libraries and Swift packages** that contain pure logic nonisolated, so they stay usable from any context. Both settings can be set per target. If you adopt Swift 6 language mode in an existing codebase, migrate target by target and use the warning-level strict concurrency setting first.

### Actors for shared mutable state

A cache, a token store or a download coordinator is the classic actor.

```swift
actor TokenStore {
    private var token: String?
    private var refreshTask: Task<String, Error>?

    func validToken(refresh: @Sendable @escaping () async throws -> String) async throws -> String {
        if let token { return token }
        if let refreshTask { return try await refreshTask.value }
        let task = Task { try await refresh() }
        refreshTask = task
        defer { refreshTask = nil }
        let new = try await task.value
        token = new
        return new
    }

    func clear() { token = nil }
}
```

This coalesces concurrent refresh calls into one, which is a real bug source in apps that fire several requests at launch. Note actor re-entrancy: any `await` inside an actor method lets other calls interleave, so re-check your assumptions after each suspension point.

### Structured concurrency

```swift
func loadDashboard() async throws -> Dashboard {
    async let profile = api.profile()
    async let orders = api.recentOrders()
    async let recs = api.recommendations()
    return try await Dashboard(profile: profile, orders: orders, recs: recs)
}
```

For a variable number of children, use `withThrowingTaskGroup`, and limit concurrency yourself if the group could fan out to hundreds of network calls.

### `Sendable` in practice

Types crossing isolation boundaries must be `Sendable`. Make DTOs and domain values `struct`s with `Sendable` members, mark API clients as `Sendable` final classes with immutable state or as actors, and avoid passing `@Observable` models into background tasks; pass values in and results out.

### Common concurrency mistakes

- Calling `DispatchQueue.main.async` inside async code. Use `@MainActor` or `await MainActor.run`.
- Using `Task.detached` as a default. It drops priority and actor context and cancellation inheritance; use it only when you truly want detachment.
- Blocking the main actor with synchronous work inside `async` functions. `async` does not mean off-thread.
- Suppressing warnings with `@unchecked Sendable` without synchronisation.
- Forgetting `try Task.checkCancellation()` in loops.

## Persistence: SwiftData versus Core Data

### When to pick which

| Need | SwiftData | Core Data |
|---|---|---|
| New app, local data, simple relationships | Excellent fit | Works, more boilerplate |
| Tight SwiftUI integration (`@Query`) | Native | Via `@FetchRequest` |
| CloudKit sync | Supported, with model constraints | Mature (`NSPersistentCloudKitContainer`) |
| Complex migrations, custom mapping models | Improving; verify current capabilities | Mature and well-understood |
| Shared stores between app and extensions | Possible via App Group container | Mature patterns |
| Very large datasets, batch operations, fetch tuning | Good for moderate scale; profile | More control (batch APIs, faulting) |
| Existing Core Data codebase | Migrate selectively | Keep |
| Need to target below iOS 17 | Not available | Available |

SwiftData sits on top of the Core Data stack and is an excellent default for new apps targeting iOS 17+. It is not magic: you must still design your schema, think about migrations, and measure fetch performance. For anything where data loss would be a business problem, rehearse the migration path with real data before shipping.

### A SwiftData model and container

```swift
import SwiftData

@Model
final class Task {
    var title: String
    var notes: String
    var isDone: Bool
    var dueDate: Date?
    @Relationship(deleteRule: .cascade) var subtasks: [Subtask] = []

    init(title: String, notes: String = "", isDone: Bool = false, dueDate: Date? = nil) {
        self.title = title
        self.notes = notes
        self.isDone = isDone
        self.dueDate = dueDate
    }
}

@Model
final class Subtask {
    var title: String
    var isDone: Bool = false
    init(title: String) { self.title = title }
}

@main
struct TasksApp: App {
    var body: some Scene {
        WindowGroup { TaskListView() }
            .modelContainer(for: [Task.self, Subtask.self])
    }
}
```

Naming a model `Task` collides with Swift's concurrency `Task`; in a real project, use `TodoItem` or similar. I use `Task` here only to illustrate the macro and recommend you do not copy the name.

### Querying in views and in models

```swift
struct TodoListView: View {
    @Environment(\.modelContext) private var context
    @Query(filter: #Predicate<TodoItem> { !$0.isDone },
           sort: \TodoItem.dueDate)
    private var open: [TodoItem]

    var body: some View {
        List {
            ForEach(open) { item in
                Text(item.title)
            }
            .onDelete { offsets in
                offsets.map { open[$0] }.forEach(context.delete)
            }
        }
    }
}
```

`@Query` is convenient but ties the view to the persistence type. In larger apps, hide SwiftData behind a repository protocol returning plain structs, so tests and previews do not need a container, and so you can swap the store later. A reasonable split: use `@Query` in small, leaf screens, and a repository in features with business logic.

### Threading and `ModelContext`

`ModelContext` and model objects are not `Sendable`. The main context is bound to the main actor. For background work, create a `ModelActor` (via the `@ModelActor` macro) which owns its own context, and exchange identifiers or plain value copies with the UI. Check the current documentation for the exact macro usage and for the guidance on passing `PersistentIdentifier` values across actors.

### Migrations

Use `VersionedSchema` and a `SchemaMigrationPlan` for non-trivial model changes. Lightweight migration handles adding optional properties and many renames if you annotate with `@Attribute(originalName:)`. Always ship a migration test that opens a store created by the previous release's schema.

## Dependency injection

SwiftUI already has a DI mechanism: the environment. Combined with protocol-typed initialiser injection for models, you rarely need a framework.

```swift
protocol ProfileService: Sendable {
    func fetch() async throws -> Profile
    func update(displayName: String, bio: String) async throws
}

struct LiveProfileService: ProfileService {
    let client: APIClient
    func fetch() async throws -> Profile { try await client.get("/me") }
    func update(displayName: String, bio: String) async throws {
        try await client.send("/me", body: ["displayName": displayName, "bio": bio])
    }
}

struct MockProfileService: ProfileService {
    var profile = Profile(displayName: "Ada", bio: "Programmer")
    func fetch() async throws -> Profile { profile }
    func update(displayName: String, bio: String) async throws {}
}

@MainActor
@Observable
final class ServiceContainer {
    let profile: any ProfileService
    let orders: any OrderService

    init(profile: any ProfileService, orders: any OrderService) {
        self.profile = profile
        self.orders = orders
    }

    static func live() -> ServiceContainer {
        let client = APIClient(baseURL: URL(string: "https://api.example.com")!)
        return ServiceContainer(profile: LiveProfileService(client: client),
                                orders: LiveOrderService(client: client))
    }

    static func preview() -> ServiceContainer {
        ServiceContainer(profile: MockProfileService(), orders: MockOrderService())
    }
}
```

Rules that keep this healthy:

- **Models take protocols in `init`.** Views never call services directly.
- **One composition root** (the `App` struct) builds the graph.
- **Previews inject `preview()`** so they never hit the network.
- **No global singletons for anything with state.** `static let shared` makes tests order-dependent.
- If you want property-wrapper-style DI at scale, the Point-Free `swift-dependencies` library is a well-regarded option; evaluate it only when the plain approach hurts.

## Architecture options: plain, MVVM, TCA

| Criterion | Plain SwiftUI + `@Observable` models | MVVM with explicit view models | The Composable Architecture (TCA) |
|---|---|---|---|
| Boilerplate | Lowest | Low to medium | Highest |
| Testability | Good if logic lives in models | Good | Excellent, exhaustive state testing |
| Learning curve | Lowest | Low | Steep |
| Side-effect modelling | Async methods | Async methods | First-class effects and dependencies |
| Navigation | Router object | Router object | Built-in state-driven navigation |
| Dependency | Apple only | Apple only | Third-party framework (verify version and Swift support) |
| Team scaling | Needs conventions | Needs conventions | Conventions enforced by the framework |
| Risk | Spaghetti without discipline | Same | Framework churn, compile times |

### My recommendation

For most apps: **plain SwiftUI with `@Observable` models**, which is MVVM in everything but name, because an observable model with state and intent methods is a view model. Do not create a `ViewModel` suffix cult; name types by what they are (`CartModel`, `CheckoutModel`). Reach for TCA when your team wants deterministic reducers, large state machines with many effects, exhaustive tests that assert every state change, and is willing to learn the framework. It is a legitimate choice with strong documentation from Point-Free; evaluate its current release and minimum OS in its repository before adopting.

### Layout that scales

```text
ShopApp/
├── App/
│   ├── ShopApp.swift            # composition root
│   ├── Router.swift
│   └── ServiceContainer.swift
├── Features/
│   ├── Catalog/
│   │   ├── CatalogView.swift
│   │   ├── CatalogModel.swift
│   │   └── ProductRow.swift
│   ├── Cart/
│   └── Checkout/
├── Domain/                      # plain structs, no SwiftUI
├── Services/                    # API client, repositories, protocols
├── DesignSystem/                # colors, typography, shared components
└── Tests/
```

Push big features into local Swift packages once compile times or boundaries demand it. A package per feature with a public entry view and a protocol surface enforces dependency direction and speeds incremental builds.

## A full worked feature: product catalog with search, cart and checkout

This feature uses everything above: an `@Observable` model, a protocol service, `.task(id:)` search with debounce, typed navigation, an actor-protected cart, and accessibility. It is deliberately compact but complete enough to copy.

### Domain and service

```swift
import Foundation

struct Product: Identifiable, Hashable, Sendable, Codable {
    let id: Int
    let name: String
    let price: Decimal
    let imageURL: URL?
}

struct CartLine: Identifiable, Hashable, Sendable {
    let product: Product
    var quantity: Int
    var id: Product.ID { product.id }
    var total: Decimal { product.price * Decimal(quantity) }
}

protocol CatalogService: Sendable {
    func search(_ query: String) async throws -> [Product]
}

struct LiveCatalogService: CatalogService {
    let session: URLSession
    let baseURL: URL

    func search(_ query: String) async throws -> [Product] {
        var comps = URLComponents(url: baseURL.appending(path: "products"), resolvingAgainstBaseURL: false)!
        comps.queryItems = [URLQueryItem(name: "q", value: query)]
        let (data, response) = try await session.data(from: comps.url!)
        guard let http = response as? HTTPURLResponse, (200..<300).contains(http.statusCode) else {
            throw URLError(.badServerResponse)
        }
        return try JSONDecoder().decode([Product].self, from: data)
    }
}
```

### Cart actor and model

```swift
actor CartStore {
    private var lines: [Product.ID: CartLine] = [:]

    func add(_ product: Product) -> [CartLine] {
        if var line = lines[product.id] {
            line.quantity += 1
            lines[product.id] = line
        } else {
            lines[product.id] = CartLine(product: product, quantity: 1)
        }
        return snapshot()
    }

    func remove(_ id: Product.ID) -> [CartLine] {
        lines[id] = nil
        return snapshot()
    }

    func snapshot() -> [CartLine] {
        lines.values.sorted { $0.product.name < $1.product.name }
    }
}

@MainActor
@Observable
final class CartModel {
    private(set) var lines: [CartLine] = []
    @ObservationIgnored private let store = CartStore()

    var total: Decimal { lines.reduce(0) { $0 + $1.total } }
    var count: Int { lines.reduce(0) { $0 + $1.quantity } }

    func add(_ product: Product) async { lines = await store.add(product) }
    func remove(_ id: Product.ID) async { lines = await store.remove(id) }
}
```

### Catalog model with debounced search

```swift
@MainActor
@Observable
final class CatalogModel {
    enum Phase: Equatable {
        case idle
        case loading
        case loaded([Product])
        case failed(String)
    }

    var query = ""
    private(set) var phase: Phase = .idle

    @ObservationIgnored private let service: any CatalogService

    init(service: any CatalogService) { self.service = service }

    func search() async {
        let q = query.trimmingCharacters(in: .whitespaces)
        guard !q.isEmpty else { phase = .idle; return }
        phase = .loading
        do {
            try await Task.sleep(for: .milliseconds(300)) // debounce; throws if cancelled
            let result = try await service.search(q)
            phase = .loaded(result)
        } catch is CancellationError {
            // A newer query superseded this one; leave state as is.
        } catch {
            phase = .failed(error.localizedDescription)
        }
    }
}
```

### Views

```swift
struct CatalogView: View {
    @State private var model: CatalogModel
    @Environment(Router.self) private var router
    @Environment(CartModel.self) private var cart

    init(service: any CatalogService) {
        _model = State(initialValue: CatalogModel(service: service))
    }

    var body: some View {
        @Bindable var model = model
        Group {
            switch model.phase {
            case .idle:
                ContentUnavailableView("Search products", systemImage: "magnifyingglass")
            case .loading:
                ProgressView().frame(maxWidth: .infinity, maxHeight: .infinity)
            case .loaded(let products) where products.isEmpty:
                ContentUnavailableView.search(text: model.query)
            case .loaded(let products):
                List(products) { product in
                    ProductRow(product: product) {
                        Task { await cart.add(product) }
                    }
                    .contentShape(Rectangle())
                    .onTapGesture { router.push(.productDetail(id: product.id)) }
                }
            case .failed(let message):
                ContentUnavailableView("Something went wrong",
                                       systemImage: "exclamationmark.triangle",
                                       description: Text(message))
            }
        }
        .navigationTitle("Catalog")
        .searchable(text: $model.query)
        .task(id: model.query) { await model.search() }
        .toolbar {
            ToolbarItem(placement: .primaryAction) {
                Button { router.push(.cart) } label: {
                    Label("Cart, \(cart.count) items", systemImage: "cart")
                }
            }
        }
    }
}

struct ProductRow: View {
    let product: Product
    let onAdd: () -> Void

    var body: some View {
        HStack {
            AsyncImage(url: product.imageURL) { image in
                image.resizable().scaledToFill()
            } placeholder: {
                Color.secondary.opacity(0.15)
            }
            .frame(width: 56, height: 56)
            .clipShape(.rect(cornerRadius: 10))
            .accessibilityHidden(true)

            VStack(alignment: .leading) {
                Text(product.name).font(.headline)
                Text(product.price, format: .currency(code: "USD"))
                    .font(.subheadline).foregroundStyle(.secondary)
            }
            Spacer()
            Button("Add", systemImage: "plus.circle", action: onAdd)
                .labelStyle(.iconOnly)
                .buttonStyle(.borderless)
                .accessibilityLabel("Add \(product.name) to cart")
        }
        .accessibilityElement(children: .combine)
    }
}
```

Notes on this code: the debounce works because `.task(id:)` cancels the previous run whenever the query changes, which makes `Task.sleep` throw `CancellationError`. The row uses a combined accessibility element so VoiceOver reads the product as one item, with a labelled add action. The currency uses a format style rather than a manually built string, which handles localisation.

### Tests with Swift Testing

Swift Testing is Apple's modern test framework, bundled with Xcode 16 and later. It uses `@Test` and `@Suite`, `#expect` and `#require` macros, parameterised tests, and traits.

```swift
import Testing
@testable import Shop

struct StubCatalogService: CatalogService {
    var result: Result<[Product], Error>
    func search(_ query: String) async throws -> [Product] { try result.get() }
}

@MainActor
@Suite("CatalogModel")
struct CatalogModelTests {
    let sample = Product(id: 1, name: "Mug", price: 12, imageURL: nil)

    @Test func emptyQueryResetsToIdle() async {
        let model = CatalogModel(service: StubCatalogService(result: .success([])))
        model.query = "   "
        await model.search()
        #expect(model.phase == .idle)
    }

    @Test func successfulSearchLoads() async {
        let model = CatalogModel(service: StubCatalogService(result: .success([sample])))
        model.query = "mug"
        await model.search()
        #expect(model.phase == .loaded([sample]))
    }

    @Test func failureProducesFailedPhase() async {
        let model = CatalogModel(service: StubCatalogService(result: .failure(URLError(.notConnectedToInternet))))
        model.query = "mug"
        await model.search()
        guard case .failed = model.phase else {
            Issue.record("Expected failed phase")
            return
        }
    }

    @Test("Cart totals", arguments: [(1, Decimal(12)), (3, Decimal(36))])
    func cartTotals(quantity: Int, expected: Decimal) {
        let line = CartLine(product: sample, quantity: quantity)
        #expect(line.total == expected)
    }
}
```

Use XCTest and XCUITest for UI automation and performance tests, since Swift Testing does not replace them there; both can coexist in one target. A debounce test that waits 300 milliseconds is slow; for real projects inject a clock (the `Clock` protocol) so tests can run instantly.

### Previews

```swift
#Preview("Loaded") {
    NavigationStack {
        CatalogView(service: StubCatalogService(result: .success([
            Product(id: 1, name: "Mug", price: 12, imageURL: nil),
            Product(id: 2, name: "Kettle", price: 39, imageURL: nil),
        ])))
    }
    .environment(Router())
    .environment(CartModel())
}
```

Previews are a testing surface. Include previews for empty, loading, error and large-text states, and snapshot them in CI if your team uses a snapshot library.

## Performance and profiling with Instruments

SwiftUI performance work is measurement work. Do not guess; do not sprinkle `.equatable()` everywhere.

### The workflow

1. **Reproduce on a real device**, release configuration, with realistic data. Simulators and debug builds mislead.
2. **Profile with Instruments.** Use the SwiftUI template (which in recent Xcode versions includes view body and update tracking), Time Profiler for CPU, Animation Hitches for scroll and animation, Allocations and Leaks for memory. Check the Xcode release notes for the current template names.
3. **Find the cause category**: expensive `body`, too-wide invalidation, layout thrash, image decoding on the main thread, main-actor blocking, or a large list without identity.
4. **Fix, re-measure, and keep the trace** as a baseline.

### Common fixes

| Symptom | Likely cause | Fix |
|---|---|---|
| Entire screen re-renders on small change | A view reads a broad model or an environment value that changes often | Split into subviews that read only what they need; pass values, not models |
| Scroll hitches in a list | Heavy work in row `body`, unstable ids, images decoded synchronously | Stable `Identifiable` ids, precompute display values, downsample images, use `LazyVStack` or `List` |
| Typing lag in a text field | Model update triggers an expensive derived computation | Debounce, move computation off the main actor with `@concurrent`, cache results |
| Slow launch | Work in `App.init` or first-screen `init` | Defer to `.task`, lazy-load services |
| Memory growth | Retaining large models in navigation history or caches | Store ids in the path, use `NSCache`, check leaks |
| Animation jank | Layout in the animation path, shadows and blurs on large views | Animate transforms and opacity; avoid animating layout of big hierarchies |

### Rules of thumb

- Give `ForEach` and `List` stable identity. `id: \.self` on non-unique values creates subtle bugs.
- Keep `body` cheap: hoist formatters and sorted arrays out of it (compute in the model, cache them).
- Prefer value-driven subviews to AnyView; `AnyView` defeats diffing.
- Use `Self._printChanges()` temporarily in debug to see which property triggered a view update; remove it before shipping.
- Verify launch time and hitch rate with MetricKit and Xcode Organizer in production, not only in your lab.

## Accessibility as a feature, not a pass

SwiftUI gives you a lot for free, but only if you use semantic building blocks.

- **Use system controls and text styles.** `Text` with `.font(.body)` scales with Dynamic Type; fixed point sizes do not.
- **Label what is not text.** Icon-only buttons need `accessibilityLabel`. Decorative images get `accessibilityHidden(true)`.
- **Group meaningfully.** `accessibilityElement(children: .combine)` for rows; avoid exposing five separate elements for one card.
- **Support actions.** `accessibilityAction` for swipe or long-press functionality VoiceOver users cannot discover.
- **Test settings.** Larger Text (including the largest accessibility sizes), Bold Text, Increase Contrast, Reduce Transparency, Reduce Motion, Differentiate Without Color, and VoiceOver.
- **Respect `@Environment(\.accessibilityReduceMotion)`** and `\.accessibilityReduceTransparency`, particularly with glass effects and parallax.
- **Minimum touch targets** of about 44 by 44 points.
- Use the **Accessibility Inspector** and the audit in UI tests (`performAccessibilityAudit()` exists in XCUITest for recent SDKs; check availability for your target).

## Adopting Liquid Glass and iOS 26 design properly

Liquid Glass is the translucent, refractive material introduced with the iOS 26 generation across Apple platforms. It is more than a visual treatment: it changes how navigation chrome, controls and layers relate to content. The most important thing to understand is that **the platform does most of the work for you when you use standard components and rebuild with the new SDK**.

### Step one: rebuild and look

Build with the iOS 26 SDK (Xcode 26) and run your existing app. Standard navigation bars, tab bars, toolbars, sheets, menus, alerts and many controls adopt the new look automatically. Many apps will look broadly right immediately, and the most valuable work is **removing** things you added to fight the old system look:

- Custom navigation bar backgrounds, tab bar backgrounds and toolbar tints that now conflict with the system material.
- Custom blur backgrounds behind toolbars or sheets.
- Hard separators and opaque containers that block content from showing beneath the bars.

If you must delay adoption, Apple has provided a temporary Info.plist opt-out key (`UIDesignRequiresCompatibility`) in the iOS 26 SDK era. Treat it as a short-term escape hatch; verify its current status and whether it is still honoured in the SDK you build with, because Apple has indicated such compatibility measures are not permanent.

### Use system components first

| Need | Use | Notes |
|---|---|---|
| Navigation chrome | `NavigationStack`, `.toolbar` | Toolbar items group into glass capsules automatically |
| Tabs | `TabView` with `Tab` | Floating tab bar; use `.tabBarMinimizeBehavior(.onScrollDown)` to let it minimise while scrolling (verify availability) |
| Search | `.searchable`, and a `Tab` with the search role | Search can live in the tab bar on iPhone |
| Sheets | `.sheet` with presentation detents | Partial-height sheets use the glass material; remove custom backgrounds |
| Buttons | `.buttonStyle(.glass)` or `.glassProminent` | Verify exact style names in the current docs |
| Menus, alerts, controls | Standard components | Update automatically |

### Custom glass: `glassEffect` and `GlassEffectContainer`

For your own floating controls, apply the `glassEffect` modifier, optionally with a shape and style, and group neighbouring glass elements in a `GlassEffectContainer` so they sample and blend consistently and perform well.

```swift
struct FloatingActions: View {
    @Namespace private var namespace
    @State private var expanded = false

    var body: some View {
        GlassEffectContainer(spacing: 16) {
            HStack(spacing: 16) {
                Button("Share", systemImage: "square.and.arrow.up") { }
                    .buttonStyle(.glass)
                    .glassEffectID("share", in: namespace)

                if expanded {
                    Button("Bookmark", systemImage: "bookmark") { }
                        .buttonStyle(.glass)
                        .glassEffectID("bookmark", in: namespace)
                }

                Button(expanded ? "Less" : "More", systemImage: "ellipsis") {
                    withAnimation(.bouncy) { expanded.toggle() }
                }
                .buttonStyle(.glassProminent)
                .glassEffectID("more", in: namespace)
            }
        }
        .padding()
    }
}

struct Badge: View {
    var body: some View {
        Text("New")
            .font(.caption.bold())
            .padding(.horizontal, 12).padding(.vertical, 6)
            .glassEffect(.regular.tint(.blue).interactive(), in: .capsule)
    }
}
```

`glassEffectID(_:in:)` with a namespace lets glass shapes morph into each other during transitions. The signatures above reflect the iOS 26 SDK as documented at the time of writing; confirm `glassEffect`, `GlassEffectContainer`, `.glass` and `.glassProminent` details in Apple's "Applying Liquid Glass to custom views" documentation, since these APIs are new and refined in point releases.

### The rules that keep it from looking terrible

1. **Glass is for the functional layer that floats above content**: controls, navigation, toolbars. Content (lists, cards, article text) should not be glass.
2. **Never stack glass on glass.** Group related elements in one container instead.
3. **Use tint sparingly**, for primary actions and state, not as decoration.
4. **Let content extend under bars.** Use the system's scroll-edge effects, and where you have a large background image behind a sidebar, look at the background-extension modifier introduced for this purpose (verify the name and availability in the docs).
5. **Check legibility.** Glass over busy imagery can reduce contrast. Test over light, dark, and photographic content, and with Increase Contrast and Reduce Transparency, which change the material.
6. **Respect concentricity.** Corners of nested shapes and the device's corner radius should align; use the system's concentric shape APIs where available (verify) rather than hard-coding radii.
7. **Do not recreate glass with materials and blurs** on old OS versions in a way that looks inconsistent. Use availability checks and a plain fallback for earlier systems.

```swift
extension View {
    @ViewBuilder
    func floatingControlBackground() -> some View {
        if #available(iOS 26, *) {
            self.glassEffect(.regular, in: .capsule)
        } else {
            self.background(.ultraThinMaterial, in: Capsule())
        }
    }
}
```

### Design-system housekeeping for iOS 26

- Replace hard-coded bar colours with semantic colours and let the system adapt.
- Audit icons: SF Symbols 7 era updates and the new icon format for app icons (Icon Composer in Xcode 26) matter for the home-screen look. Verify the current tooling.
- Review every custom sheet, popover and toolbar against the new visuals on small and large devices, in light and dark.
- Update screenshots and marketing assets; the glass look is highly visible in the App Store.

## A step-by-step lab: migrate one screen

This lab takes a typical legacy screen and brings it up to this architecture in about two hours. Use it on a real screen in your codebase.

1. **Baseline.** Record a launch trace and a scroll trace on a physical device. Write down hitch rate and body-update counts from the SwiftUI instrument.
2. **Extract the model.** Move state and logic from the view or `ObservableObject` into an `@Observable` class. Keep the same method names to minimise churn.
3. **Swap property wrappers.** `@StateObject` becomes `@State`; `@ObservedObject` becomes a plain property or `@Bindable`; `@EnvironmentObject` becomes `@Environment(Type.self)`; `@Published` is removed.
4. **Protocol the service.** Introduce a protocol and inject it through `init`. Add a mock.
5. **Move to `.task`.** Replace `onAppear` plus `Task` with `.task` or `.task(id:)`.
6. **Type the navigation.** Replace boolean-driven links with a `Route` enum and `navigationDestination(for:)`.
7. **Add tests.** Write Swift Testing tests for the model's success, empty and failure paths.
8. **Accessibility sweep.** Large text, VoiceOver, reduced motion.
9. **Liquid Glass sweep.** Rebuild with Xcode 26; delete custom chrome; verify on iOS 26 and your minimum OS.
10. **Re-profile and compare** against step 1.

Success criteria: fewer body updates for the same interaction, no new data-race warnings, tests green, and no regressions at the largest Dynamic Type size.

## Where this usually goes wrong

1. Constructing models in `body` instead of owning them with `@State`.
2. Using `@Bindable` as an owner. It does not retain; the parent must own.
3. Mixing `ObservableObject` and `@Observable` in one hierarchy without a plan.
4. `onAppear { Task { } }` instead of `.task`.
5. Fat views that contain networking, mapping and formatting; extract to models and services.
6. Unstable `ForEach` identity (indices, `\.self` on duplicates, random UUIDs generated in `body`).
7. `AnyView` everywhere, which defeats diffing.
8. Passing entire models to tiny leaf views, widening invalidation.
9. Singletons for state that make previews and tests unreliable.
10. Blocking the main actor with synchronous parsing, image decoding or Core Data fetches.
11. Silencing concurrency warnings with `@unchecked Sendable` or `nonisolated(unsafe)` without a proof.
12. Glass on everything. Applying `glassEffect` to cards and list rows destroys the hierarchy that glass is meant to express.
13. Ignoring minimum OS in availability checks, shipping iOS 26-only calls without `#available`.
14. Not testing at the largest accessibility text size.

## When not to do this

- Do not migrate a stable `ObservableObject` codebase just for fashion. Migrate when you touch the code, or when invalidation costs show up in profiles.
- Do not adopt TCA for a small app because a conference talk said so. The ceremony outweighs the benefit under about a dozen screens with simple state.
- Do not use SwiftData where you need guaranteed, rehearsed migrations of critical data without prototyping the migration first; Core Data's track record may be the safer call.
- Do not wrap everything in a repository protocol if the data source is a single trivial `@Query` in a leaf screen.
- Do not put glass effects on content or force Liquid Glass emulation on older OS versions.
- Do not use SwiftUI for everything: a complex text editor, a custom collection layout with exotic behaviour or a camera preview may still be best hosted in UIKit via `UIViewRepresentable`.
- Do not turn on strict concurrency complete across a million-line codebase in one commit. Migrate by target.

## Pre-release checklist

```text
ARCHITECTURE
[ ] Models are @Observable and own their state; views own models with @State
[ ] No service calls in views; services injected as protocols
[ ] Routes are typed; deep links tested
[ ] No models created in body or in hot initialisers

CONCURRENCY
[ ] UI-facing models on the main actor (explicit or via default isolation)
[ ] Shared mutable state in actors; no unchecked Sendable without justification
[ ] .task used for view-scoped async work; cancellation verified
[ ] Heavy work marked @concurrent or run off the main actor

DATA
[ ] Migration tested from the previous shipped schema
[ ] Background contexts used for large imports; no main-thread fetches of big sets

QUALITY
[ ] Swift Testing suites cover model logic (success, empty, error)
[ ] Previews for empty, loading, error, large text, dark mode
[ ] Instruments: no hitches above budget on target device; no leaks

ACCESSIBILITY
[ ] VoiceOver walkthrough of every flow
[ ] Largest Dynamic Type, Bold Text, Increase Contrast, Reduce Transparency, Reduce Motion
[ ] Touch targets at least 44 points

IOS 26 DESIGN
[ ] Built with the iOS 26 SDK; custom bar and sheet chrome removed
[ ] glassEffect only on custom floating controls, grouped in GlassEffectContainer
[ ] Availability fallbacks for earlier OS versions
[ ] Screenshots and icons updated
```

## Questions that come up

**Can I use `@Observable` and still support iOS 16?**
Not directly; Observation requires iOS 17. Keep `ObservableObject` for iOS 16 targets or raise the minimum.

**Why does my view not update when a property changes?**
Common causes: the property is marked `@ObservationIgnored`, you mutated a reference not read by `body`, you mutated off the main actor and the update was lost or delayed, or the model is a struct copied rather than a shared class.

**Is `NavigationPath` or a typed array better?**
A typed array of an enum is easier to test, persist and reason about. Use `NavigationPath` only for mixed heterogeneous types.

**Do I need a third-party DI container?**
Usually no. Initialiser injection plus the SwiftUI environment is enough for most apps.

**How do I adopt Liquid Glass without breaking older iOS versions?**
Rebuild with the new SDK, use standard components, and wrap custom `glassEffect` calls in `#available(iOS 26, *)` with a material fallback.

**Will Liquid Glass hurt accessibility?**
It can reduce contrast over busy content. The system adapts with Reduce Transparency and Increase Contrast, but you must test legibility yourself.

## Sources and docs

- [SwiftUI documentation](https://developer.apple.com/documentation/swiftui)
- [Observation framework](https://developer.apple.com/documentation/observation)
- [Managing model data in your app](https://developer.apple.com/documentation/swiftui/managing-model-data-in-your-app)
- [NavigationStack](https://developer.apple.com/documentation/swiftui/navigationstack)
- [SwiftData](https://developer.apple.com/documentation/swiftdata)
- [Swift Testing](https://developer.apple.com/documentation/testing)
- [The Swift Programming Language: Concurrency](https://docs.swift.org/swift-book/documentation/the-swift-programming-language/concurrency/)
- [Swift Evolution proposals](https://github.com/swiftlang/swift-evolution)
- [Applying Liquid Glass to custom views](https://developer.apple.com/documentation/SwiftUI/Applying-Liquid-Glass-to-custom-views)
- [Human Interface Guidelines: Materials](https://developer.apple.com/design/human-interface-guidelines/materials)
- [Understanding and improving SwiftUI performance](https://developer.apple.com/documentation/Xcode/understanding-and-improving-swiftui-performance)
- [The Composable Architecture](https://github.com/pointfreeco/swift-composable-architecture)
- [Accessibility for SwiftUI](https://developer.apple.com/documentation/swiftui/view-accessibility)
