skip to content

Mock Data and Canvas

The #Preview macro renders a view at design time with traits, sample data and @Previewable state. Interviewers ask how to keep previews fast and fed with mocks instead of the network.

on this pageshow

explore

questions

5

How do you keep a SwiftUI view's previews fast and offline when the screen normally loads its feed from a network client?

level: middleimportance: must knowfreq 50%

answer

  1. previews run the real view
  2. split content from loading
  3. inject through init or environment
  4. fixtures and #if DEBUG

basics

~20 s

A SwiftUI preview runs the view's real code, so a client built inside the view calls the network. Inject the client through init or the environment, give previews a mock with fixtures, and fence that code with #if DEBUG.

solid answer

~40 s

Previews build and run the view, so a `task` that calls a live client makes every preview slow, flaky and dependent on the server. I split the screen: a content view that takes plain values (`FeedView(posts:)`) and previews from literals, and a thin container that loads data through a protocol such as `FeedLoading`. The container gets its loader through its initializer or the environment, whether that is an `@Entry` value or an `@Observable` store passed with `.environment(_:)`, so the preview hands it a mock that returns fixtures: empty, normal, very long, or an error. If a view reads an observable object by type and the preview forgets to inject it, SwiftUI throws. Mocks and the previews that use them sit in `#if DEBUG` so they don't ship.

code

swift · 35 lines
swift
import SwiftUI

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

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

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.loadFeed()) ?? [] }
    }
}

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

#Preview("Loaded") {
    FeedScreen(loader: MockFeedLoader(posts: [Post(id: 1, text: "Hello")]))
}

#Preview("Empty") {
    FeedScreen(loader: MockFeedLoader(posts: []))
}
#endif

go deeper

for a junior

Recall that a preview runs the view for real, so the view needs sample data or a mock instead of the live server.

for a middle

Explain the injection routes, initializer, @Entry environment value or observable object, and why a missing environment object throws in a preview.

for a senior

Structure screens so most previews take plain values, give mocks knobs for empty, long, error and slow states, and keep all of it out of release builds.

for a principal

Make previewability a review criterion: a screen that cannot render offline in every state usually also resists testing, which is a design smell worth flagging early.

## Why a preview hits the network at all A SwiftUI preview is not a screenshot. Xcode builds the closure you wrote in `#Preview` and runs the view: its initializer, its `body` and its modifiers. Apple describes previews as **dynamic and interactive**, so whatever the view does when it appears also happens at design time, including a `task` that calls a live API client. If a feed screen creates its own `URLSession` client, or reaches for a shared singleton, every preview of it: - **waits on the network**, so it renders slowly or shows a spinner forever; - **varies with the server**, so yesterday's preview and today's look different; - **needs credentials and a reachable backend**, which a designer's machine or an offline train ride does not have; - **cannot show rare states**, such as an empty feed, a 10,000-character post or a failed request, on demand. The fix is not a preview feature. It is making the view's data **injectable** so the preview can hand it something deterministic. ## Step by step: making a screen previewable 1. **Split content from loading.** Give the visual part a plain view that takes values (`FeedView(posts: [Post])`, plus maybe `isLoading` and an error). Most previews then need no service at all, just literals. 2. **Hide the client behind a small protocol.** For example, `protocol FeedLoading: Sendable { func loadFeed() async throws -> [Post] }`. The live type talks to the server, and a mock returns fixtures. 3. **Inject it.** Pass it through the initializer (`FeedScreen(loader:)`), or put it in the environment: a custom `EnvironmentValues` entry declared with `@Entry`, or an `@Observable` store placed with `.environment(store)` and read with `@Environment(FeedStore.self)`. 4. **Keep sample data as static fixtures.** `Post.samples`, `Post.veryLong` and an empty array make each state one line to preview. 5. **Fence preview-only code.** Wrap the mock types, the fixtures that only previews use, and the previews that use them in the same `#if DEBUG` block, so a build without the `DEBUG` condition, such as a standard Release configuration, compiles none of them. ## Choosing where the mock goes | Injection route | How the preview supplies the mock | Watch out for | |---|---|---| | initializer parameter | `FeedScreen(loader: MockFeedLoader(...))` | long init lists on deep screens | | custom environment value (`@Entry`) | `.environment(\.feedLoader, MockFeedLoader())` | the entry's default value is what runs if you forget | | `@Observable` object in the environment | `.environment(FeedStore.preview)` | reading a missing object throws | That last row trips people up. Apple's documentation for `Environment` says that when a view reads an object by its type and **that object isn't in the environment, SwiftUI throws an exception**. In the app, the root view injects the store. In a preview of a leaf view, nobody does, unless the preview adds `.environment(...)` itself. Declaring the property optional (`FeedStore?`) makes SwiftUI return `nil` instead, at the cost of handling `nil` in the view. ## Making mocks useful, not just quiet A mock that only returns the happy path wastes most of the value. Give it knobs: - a fixed list of posts, including an **empty** list and a **very long** post; - a configurable **error** to preview the failure state; - an optional **delay** using `Task.sleep(for:)` to see the loading state, kept short so the canvas stays responsive. Keep these mocks free of real I/O. A mock that reads a large JSON file on every call reintroduces the slowness you just removed. If several previews need the same expensive setup, a shared preview modifier, available from iOS 18, can build it once. ## What this is not This is about feeding previews, not about testing. Unit tests on view models and snapshot tests are covered with SwiftUI testing. How view models own their dependencies is the subject of SwiftUI architecture. The same protocol and mock often serve all three. Here the point is narrower: a preview should render in milliseconds, offline, in exactly the state you asked for. ## Key points - Previews run your view's real code, so a live client inside the view makes previews slow and unpredictable. - Inject the dependency through `init` or the environment, and give the preview a mock with fixtures. - A view that reads an `@Observable` object by type needs the preview to inject one, or SwiftUI throws. - Fence mocks and their previews with `#if DEBUG` so they stay out of release builds.

  • How do you preview the loading and error states of the same screen?
    Give the mock knobs: a configurable error it throws, and an optional short delay with `Task.sleep(for:)` before it returns, then write one named `#Preview` per configuration. Simpler still, if the content view takes `isLoading` and an error as plain values, preview those states directly without any loader.
  • What happens if a view reads @Environment(FeedStore.self) and its preview never injects a FeedStore?
    Apple's documentation says that reading an object by type when it isn't in the environment makes SwiftUI throw an exception, so the preview crashes. Either the preview adds `.environment(FeedStore(...))`, a shared preview modifier injects it for every preview, or the view declares the property as optional and handles `nil`.
  • Why split a content view from the container that loads data?
    The content view takes plain values, so its previews need no service, no async work and no mocks: each state is a literal. Only the thin container needs an injected loader. That keeps most previews instant and makes every visual state, including rare ones, one line to show.

  • Previews are static snapshots, so a task modifier never runs at design time.
  • A view that builds its own network client is fine to preview as-is.
  • SwiftUI creates a default instance when an @Observable object is missing from the environment.
  • A preview cannot crash, so a missing environment object just renders a blank view.
  • One happy-path fixture is enough to preview a feed screen.
open as a page

In SwiftUI, how do you declare previews with the #Preview macro, and how do names and traits let one view show several states?

level: juniorimportance: should knowfreq 42%

basics

~20 s

#Preview is a freestanding macro that takes an optional name, optional traits and a closure returning the view to render. Write one named #Preview per state, and use traits such as sizeThatFitsLayout or landscapeLeft for layout and orientation.

open as a page

In a SwiftUI #Preview, how do you give a component that takes a Binding real, editable state, and what does @Previewable generate?

level: middleimportance: should knowfreq 40%

basics

~20 s

Tag a root-level @State in the #Preview body with @Previewable. The macro generates an embedded view, turns tagged declarations into its properties, and lets you pass $value as a live binding instead of a frozen .constant one.

open as a page

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%

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.

open as a page

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%

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.

open as a page