skip to content

As the iOS lead on a 40-screen SwiftUI app whose previews keep breaking or calling the network, what preview standard would you set for the team?

level: principalimportance: should knowfreq 25%

answer

  1. services come in through init or the environment
  2. one shared fixtures layer behind #if DEBUG
  3. a required list of states per screen
  4. PreviewModifier for expensive shared setup
  5. new code uses #Preview, not PreviewProvider

basics

~20 s

Treat previews as a reviewed fixture layer. Screens take their services through init or the environment, previews use shared offline mocks behind #if DEBUG, every screen previews an agreed set of states, and new code uses #Preview instead of PreviewProvider.

solid answer

~50 s

I treat previews as part of the codebase and write four rules down. First, no screen builds its own network client or store: services arrive through the initializer or the environment, typed as protocols, so a preview can hand in a fake. Second, one shared fixtures layer holds sample models and mock services, compiled only in debug builds with `#if DEBUG`, so every preview draws on the same data and none of it ships. Third, each screen previews an agreed set of states: loaded, empty, loading, error and very long content, plus dark appearance and the largest Dynamic Type size set through environment modifiers. Fourth, setup that many previews share goes into a `PreviewModifier` (iOS 18 and later), and new code uses `#Preview`, because the iOS 27 SDK deprecates `PreviewProvider`. Reviewers check the state list on a new screen the way they check its tests.

code

swift · 41 lines
swift
import SwiftUI

protocol FeedLoading: Sendable {
    func loadPosts() async throws -> [Post]
}

struct Post: Identifiable, Sendable {
    let id: Int
    let text: String
}

struct FeedScreen: View {
    let loader: any FeedLoading
    @State private var posts: [Post] = []

    var body: some View {
        List(posts) { Text($0.text) }
            .task { posts = (try? await loader.loadPosts()) ?? [] }
    }
}

#if DEBUG
struct MockFeedLoader: FeedLoading {
    var posts: [Post]
    func loadPosts() async throws -> [Post] { posts }
}

extension Post {
    static let samples = [Post(id: 1, text: "First light over the bay.")]
}

#Preview("Loaded") {
    FeedScreen(loader: MockFeedLoader(posts: Post.samples))
}

#Preview("Empty, dark, largest text") {
    FeedScreen(loader: MockFeedLoader(posts: []))
        .preferredColorScheme(.dark)
        .dynamicTypeSize(.accessibility5)
}
#endif

go deeper

for a junior

Recall that a preview runs the view's code, so it needs sample data and must not call the network.

for a middle

Explain injecting a service through init or the environment so a preview can pass a mock, and naming previews after states.

for a senior

Design the fixtures layer, the required states set through environment modifiers, and PreviewModifier for shared setup.

for a principal

Set and enforce the team standard: service seams, a debug-only fixtures layer, a reviewed state list and the move off PreviewProvider.

## Why previews rot in a growing app A SwiftUI preview runs the view's real code. Xcode builds the `#Preview` closure and renders whatever it returns, so anything the view does when it appears also happens on the canvas. On a small app that is a convenience. On a 40-screen app it becomes a steady source of breakage: - A screen that creates its own API client inside the view calls the network from the canvas, so its preview is slow, flaky or empty. - Each developer writes sample data inline, so ten previews hold ten slightly different fake users, and nobody updates them when the model changes. - Only the happy path is previewed, so the empty, error and very long states are first seen by users. - Older files still use `PreviewProvider`, which the iOS 27 SDK deprecates with the message "Use #Preview instead." The lead's job is to turn previews from personal scratch space into a shared, reviewed fixture layer. The standard below is what I would write down. ## Rule 1: services come in from outside A view that constructs its own service cannot be previewed offline. So a screen receives its services, either as initializer parameters or from the environment, typed as protocols rather than concrete clients. The app injects the real implementation once, near the root; a preview injects a fake. Where a service is read with `@Environment`, the preview sets it with `environment(_:_:)`; where it is a parameter, the preview passes it. The same seam serves the unit tests, so the rule pays for itself twice. ## Rule 2: one fixtures layer, kept out of release builds Sample models and mock services live in one place that every preview uses, not in each file. A mock loader returns canned data at once, or waits or throws when the loading and error states matter. Wrapping this code in `#if DEBUG` keeps it out of the release build. Shared fixtures also force a useful discipline: when the model gains a field, one file changes and every preview follows. ## Rule 3: a required list of states per screen Agree which states every screen must preview, and review them like tests: | State | Why it is required | How the preview gets it | |---|---|---| | Loaded | the normal layout | fixture data from the shared layer | | Empty | first-run and filtered-out screens | an empty array | | Loading, error | async screens | a mock that waits or throws | | Very long content | truncation and wrapping bugs | an oversized fixture | | Dark, largest text | appearance and Dynamic Type | `preferredColorScheme(_:)`, `dynamicTypeSize(_:)` | Each state is a named `#Preview`, because the canvas labels an unnamed one only by its line number. On iOS 26 and later, `#Preview(_:traits:arguments:body:)` renders one preview per element of an array, which keeps a long state list short to write; a target that still deploys to iOS 17 or 18 writes one named preview per state. Components that take a `Binding` get live state from `@Previewable @State` rather than a frozen `.constant` value, so a reviewer can interact with them. ## Rule 4: share expensive setup with PreviewModifier When many previews need the same costly context, such as a store filled with sample data or a configured set of services, a `PreviewModifier` (iOS 18 and later) builds it once in `makeSharedContext()`. The preview system caches that context and reuses it across the previews that opt in with the `.modifier` trait, and `body(content:context:)` applies it. Setup then lives in one type instead of being copied into every closure. On an iOS 17 deployment target the same job falls to a plain helper view in the fixtures layer. ## Rolling it out A standard that lives only in a wiki is ignored. To make it stick: 1. Put the state list in the pull request template for new screens. 2. Move `PreviewProvider` files to `#Preview` as they are touched; the deprecation messages name each replacement, such as `#Preview("name")` for `previewDisplayName(_:)`. 3. Treat a preview that no longer builds as a broken feature build, not an Xcode quirk. 4. Give the fixtures layer an owner, like any shared module, so it does not decay into copies. ## Trade-offs to state openly The cost is upfront work: protocols for services and a fixtures layer before the first preview. The payoff is that previews, tests and design reviews draw on the same fakes, and a new state costs one declaration. Previews show states to a person; they assert nothing, so they complement unit and UI tests rather than replace them.

  • How would you migrate a large set of PreviewProvider previews without losing coverage?
    Mechanically, file by file: each entry in `previews` becomes a `#Preview` named after its old `previewDisplayName`, and `previewLayout(.sizeThatFits)` becomes the `.sizeThatFitsLayout` trait. The iOS 27 SDK's deprecation messages name these replacements, so the compiler warnings double as the worklist, and the named previews keep every state that was covered before.
  • Why not let each developer keep sample data inline in their own previews?
    Inline fixtures drift. When the model changes, some previews are updated and others show stale shapes or stop compiling. A shared layer changes in one place, gives designers and reviewers the same named examples, and can be reused by unit tests.

  • Previews are personal scratch space, so there is nothing for a team to standardise.
  • A preview may call the real API, since it only runs on a developer's machine.
  • Ship the mock services in the release build so the previews always compile.
  • Keep writing PreviewProvider in new files for consistency with the old ones.
  • Previews of every state make UI tests unnecessary.

Assumes the iOS 27 SDK, which deprecates PreviewProvider in favour of #Preview; PreviewModifier needs iOS 18 and the arguments form of #Preview needs iOS 26.