skip to content

In SwiftUI on iOS 18 and later, how does a PreviewModifier share one mocked environment across many previews, and when is it worth using?

level: seniorimportance: nice to knowfreq 25%

answer

  1. build once, reuse everywhere
  2. a shared context the preview system caches
  3. body(content:context:) injects it
  4. attached with the .modifier trait

basics

~20 s

PreviewModifier, added in iOS 18, builds expensive mock state once in makeSharedContext(), which the preview system caches and reuses, then injects it in body(content:context:). Previews opt in with the .modifier trait, so setup lives in one place.

solid answer

~40 s

When many previews need the same environment, for example an `@Observable` `FeedStore` full of sample posts, I put the setup in a `PreviewModifier` (iOS 18). `static func makeSharedContext() async throws -> Context` builds the store once. Apple's documentation says that shared context is cached by the preview system and reused across participating previews. `body(content:context:)` returns `content.environment(context)`. Each preview opts in with `#Preview(traits: .modifier(MockFeedEnvironment()))`, usually through a named trait such as `.mockFeed`. That removes duplicated fixture code and the crash you get when a preview forgets to inject an object the view reads by type. With a `Void` context the SDK supplies `makeSharedContext()` for you. For a single preview needing one `.environment` line, a modifier is overkill.

code

swift · 37 lines
swift
import SwiftUI

@Observable
final class FeedStore {
    var posts: [String]
    init(posts: [String]) { self.posts = posts }
}

struct MockFeedEnvironment: PreviewModifier {
    static func makeSharedContext() async throws -> FeedStore {
        FeedStore(posts: (1...300).map { "Sample post \($0)" })
    }

    func body(content: Content, context: FeedStore) -> some View {
        content.environment(context)
    }
}

extension PreviewTrait where T == Preview.ViewTraits {
    @MainActor static var mockFeed: Self { .modifier(MockFeedEnvironment()) }
}

struct FeedList: View {
    @Environment(FeedStore.self) private var store

    var body: some View {
        List(store.posts, id: \.self) { Text($0) }
    }
}

#Preview("Feed", traits: .mockFeed) {
    FeedList()
}

#Preview("Feed, dark landscape", traits: .mockFeed, .landscapeLeft) {
    FeedList().preferredColorScheme(.dark)
}

go deeper

for a junior

Recall that a PreviewModifier puts shared preview setup in one place and that previews attach it with the .modifier trait.

for a middle

Explain the two requirements: makeSharedContext builds the context once, and body(content:context:) applies it to each preview's content.

for a senior

Use it to remove repeated fixture code and missing-environment crashes across a feature's previews, and plan the fallback when the deployment target is below iOS 18.

for a principal

Decide what the team's standard mocked environment contains and who owns it, so every feature previews against the same believable fixtures.

## The problem it solves Picture a social feed where a dozen views (the feed list, a post row, a profile header, a composer) all read the same `@Observable` `FeedStore` and a sample image cache from the environment. Each of their previews has to: - build a `FeedStore` and fill it with a few hundred sample posts; - remember to add `.environment(store)`, or the view throws when it reads the missing object; - repeat the same appearance setup for dark mode or a right-to-left locale. Copying that into every `#Preview` is slow, because every preview rebuilds the same expensive fixtures, and fragile, because one forgotten line crashes a preview. **`PreviewModifier`**, added in iOS 18, packages the setup once. ## The protocol `PreviewModifier` is a `@MainActor` protocol with two requirements and two associated types: | Member | Role | |---|---| | `associatedtype Context` | the shared value you build once; defaults to `Void` | | `static func makeSharedContext() async throws -> Context` | builds that value; it can `await` and `throw` | | `func body(content: Content, context: Context) -> some View` | wraps the preview's content, usually by injecting the context | | `typealias Content = PreviewModifierContent` | the type-erased content of the preview | The key sentence in Apple's documentation is that conforming types define **shared contexts that are cached by the preview system and then reused across participating previews**. In other words, `makeSharedContext()` does the expensive work once, and each preview that opts in receives the cached result in `body(content:context:)`. When `Context` is `Void`, the SDK supplies a default `makeSharedContext()`, so a modifier that only applies environment values needs nothing but `body`. ## Attaching it to previews A preview opts in through the **`.modifier(_:)` preview trait**: 1. Declare the modifier: `struct MockFeedEnvironment: PreviewModifier { ... }`. 2. Attach it: `#Preview("Feed", traits: .modifier(MockFeedEnvironment())) { FeedList() }`. 3. For readability, wrap it in a named trait in an extension on `PreviewTrait where T == Preview.ViewTraits`, so call sites read `traits: .mockFeed`. 4. Combine it with other traits as additional arguments (`traits: .mockFeed, .landscapeLeft`), or bundle several into one with `PreviewTrait`'s variadic initializer, which is also iOS 18. ## When it is worth it, and when it is not Use a preview modifier when: - **several previews need the same environment**, especially an `@Observable` object that would otherwise throw when missing; - **the setup is expensive**, such as decoding a large fixture, building an image cache or creating a database. The documentation's own example builds a model container, which is covered with SwiftData's SwiftUI integration; - **you want one place to change** what "the mocked app" means for previews. Skip it when one preview needs one `.environment(...)` line. A modifier then adds a type and indirection for no gain. Because the context is shared, build it as sample data that previews read, and don't count on one preview's changes staying invisible to the others. ## Availability `PreviewModifier`, `PreviewModifierContent`, the `.modifier(_:)` trait and `PreviewTrait`'s combining initializer all carry **iOS 18** (macOS 15) availability lines. A target that still deploys to iOS 17 needs availability annotations to use them. The simplest fallback there is a shared `View` extension that applies the same environment, which gives up the cached context. ## Diagnosing the classic failure A symptom that sends people to this API: a leaf view's preview crashes on `@Environment(FeedStore.self)`, while the app runs fine. The app's root view injects the store, but the preview starts at the leaf, so nothing above it does. Apple's `Environment` documentation says SwiftUI throws an exception when a view reads an object by type and that object isn't in the environment. A `.mockFeed` trait used by every preview that needs the store removes the whole class of crash. It also keeps the expensive fixture build out of each preview's own closure. ## Key points - `makeSharedContext()` builds expensive mock state once. The preview system caches it and reuses it across previews that use the modifier. - `body(content:context:)` injects that state, typically with `.environment(_:)`. - Attach it with `traits: .modifier(...)`, and expose it as a named trait so call sites stay short. - It is iOS 18 API. Weigh it against a plain modifier when only one preview needs the setup.

  • What do you write when the modifier only needs to set environment values such as a color scheme, with nothing expensive to share?
    Leave `Context` at its default of `Void` and implement only `body(content:context:)`, applying `preferredColorScheme(_:)` or `environment(_:_:)` to the content. The SDK's extension for a `Void` context supplies `makeSharedContext()`, so the conformance stays a few lines long.
  • How do you combine the mocked environment with other traits?
    Pass it alongside other traits in the macro, as in `#Preview(traits: .mockFeed, .landscapeLeft)`, because `traits:` takes one trait plus any number of additional ones. To reuse a combination, build one trait from several with `PreviewTrait`'s variadic initializer, which is also iOS 18 API.

  • makeSharedContext() runs again for every preview that uses the modifier.
  • A PreviewModifier is applied by calling .modifier(_:) on the view inside the preview body.
  • PreviewModifier works on an iOS 17 deployment target without any availability handling.
  • Every PreviewModifier must implement makeSharedContext(), even when it has nothing to share.
  • The .modifier trait injects the shared context into the environment with no body code.

Assumes the iOS 27 SDK; PreviewModifier, the .modifier(_:) trait and PreviewTrait's combining initializer are available from iOS 18, so an iOS 17 deployment target needs a fallback.