Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 46 ยท State and Data Flow

The Environment and Dependency Injection

Learn how SwiftUI's environment passes values down the view tree, how to add custom keys and observable models, and how to inject fake services for previews and tests.

Some data is needed by many views at many depths: the color scheme, the user's locale, a theme, the signed-in user, a network client. Passing such a value through every initializer between the top of the app and the one button that needs it is tedious and brittle. SwiftUI solves this with the environment: a bag of values attached to a view that every descendant can read.

The environment is also SwiftUI's built-in form of dependency injection. A view asks for "a quote service", not "the real network quote service", and whoever builds the tree decides which one to supply. That makes previews instant and tests deterministic. This lesson covers the values SwiftUI provides, how to add your own, how observable models travel through the environment, and how to swap services. It assumes you know @Observable and the wrapper chooser.

How values flow down the tree

An environment value is set on a view with a modifier and is visible to that view and all of its descendants, but not to its parents or siblings. A deeper modifier can override the value for just its own subtree.

flowchart TD
    A["App root<br/>accent = blue"] --> B["Settings screen"]
    A --> C["Profile screen<br/>.environment accent = green"]
    C --> D["Avatar<br/>reads green"]
    C --> E["Badge<br/>reads green"]
    B --> F["Row<br/>reads blue"]

Values are inherited downward. Profile overrides the accent for its own subtree only.

The stand-in below models exactly that rule: each node can modify a copy of the values it inherited, and its children receive the modified copy.

Swift Values inherited down a view tree

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Row still sees blue because the green override lives only inside Profile. Badge sees both the inherited green accent and its own dark scheme. This "copy, modify, hand down" model is the mental picture to keep.

Reading built-in values

You read an environment value with the @Environment property wrapper and a key path into EnvironmentValues.

Swift
struct ThemedCard: View {
    @Environment(\.colorScheme) private var colorScheme
    @Environment(\.dynamicTypeSize) private var typeSize
    @Environment(\.dismiss) private var dismiss

    var body: some View {
        VStack {
            Text(colorScheme == .dark ? "Night mode" : "Day mode")
            Button("Close") { dismiss() }
        }
    }
}

The view is re-evaluated whenever a value it reads changes, so switching the system to dark mode updates ThemedCard without any code of yours. Useful built-in values include colorScheme, locale, dynamicTypeSize, horizontalSizeClass, scenePhase, openURL and dismiss. A read-only wrapper declared private is the usual style, because the value is not yours to assign.

Adding your own environment value

For app-specific values, extend EnvironmentValues. Current Xcode versions provide the @Entry macro, which writes the key boilerplate for you:

Swift
extension EnvironmentValues {
    @Entry var accentName: String = "blue"
}

struct Header: View {
    @Environment(\.accentName) private var accentName
    var body: some View { Text("Accent: \(accentName)") }
}

// Somewhere above:
ContentView()
    .environment(\.accentName, "green")

Before @Entry, you wrote an EnvironmentKey type with a defaultValue and a computed property by hand. Existing code you meet will still look like this, and it behaves identically:

Swift
private struct AccentNameKey: EnvironmentKey {
    static let defaultValue = "blue"
}

extension EnvironmentValues {
    var accentName: String {
        get { self[AccentNameKey.self] }
        set { self[AccentNameKey.self] = newValue }
    }
}

Every key needs a default value. That default is what a view receives if nobody injected anything, which is what makes a view safe to use in a preview.

Observable models in the environment

For shared mutable state, put an @Observable object into the environment by type. The object is injected with .environment(_:) and read with @Environment(Type.self).

Swift
@Observable
final class Session {
    var userName = "Guest"
    var isSignedIn: Bool { userName != "Guest" }
}

@main
struct DemoApp: App {
    @State private var session = Session()   // the owner

    var body: some Scene {
        WindowGroup {
            RootView()
                .environment(session)        // inject by type
        }
    }
}

struct GreetingView: View {
    @Environment(Session.self) private var session

    var body: some View {
        @Bindable var session = session      // only if you need $session.userName
        TextField("Name", text: $session.userName)
    }
}

Two points matter. First, something must own the object; here the app stores it in @State. The environment only distributes it. Second, if a view reads Session.self and nothing injected one, SwiftUI traps at runtime, because there is no default. A missing injection is a programmer error, so previews of such views must inject a sample object too.

You may also see @EnvironmentObject with ObservableObject classes. It is the pre-Observation equivalent and works the same way, with the same missing-object crash. New code should prefer @Observable with @Environment(Type.self).

Injecting services

The most valuable use of the environment is to hide how something is done behind a protocol. A screen needs "a way to fetch a daily quote"; production supplies one that calls a server, a preview supplies one that returns fixed text, and a test supplies one that fails on demand.

flowchart LR
    V["QuoteView"] -->|"asks for"| P["QuoteService protocol"]
    L["LiveQuoteService<br/>(network)"] -.->|"conforms"| P
    F["FakeQuoteService<br/>(fixed data)"] -.->|"conforms"| P

The view depends on the protocol only. Which concrete type it gets is decided where the tree is built.

In real SwiftUI the pieces look like this (read-only, since it needs UIKit and the SwiftUI framework):

Swift
protocol QuoteService: Sendable {
    func dailyQuote() async throws -> String
}

extension EnvironmentValues {
    @Entry var quoteService: any QuoteService = LiveQuoteService()
}

struct QuoteView: View {
    @Environment(\.quoteService) private var service
    @State private var quote = "Loading..."

    var body: some View {
        Text(quote)
            .task {
                quote = (try? await service.dailyQuote()) ?? "No quote today"
            }
    }
}

#Preview {
    QuoteView()
        .environment(\.quoteService, FakeQuoteService(text: "Preview text"))
}

The #Preview macro builds a view on the canvas, and the .environment(\.quoteService, ...) line replaces the live service for that preview only. No network, no waiting.

The stand-in below shows the same idea with plain Swift: a protocol, two implementations and a screen model that never knows which one it holds. The "environment" is a small struct of services, and the checks at the end behave like unit tests.

Swift Swapping a service behind a protocol

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Notice that QuoteScreen was not edited for any of the four runs. Only the value passed in changed. That is dependency injection in one sentence: a type receives what it needs instead of creating it.

When not to use the environment

The environment is powerful but invisible: a view that reads @Environment(\.quoteService) does not show that dependency in its initializer. Use it for values that are genuinely cross-cutting. For data that is specific to one screen, such as the item being edited, pass it through the initializer. That keeps the dependency visible and the view easy to reason about.

Also remember that a missing observable object is a crash, not a warning. If a screen you present (a sheet, for example) stops with a missing-object error, check where the object is injected and inject it explicitly on that screen.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which views can read a value set with .environment(...) on a view V?

    Environment values flow downward. A modifier affects the view and its subtree, and a deeper modifier can override it for a smaller subtree.
  2. 2. What is required of every custom environment key?

    The default is used when no ancestor injected a value, which keeps views usable in previews.
  3. 3. A view reads @Environment(Session.self) but nothing injected a Session. What happens?

    Observable objects have no default. A missing injection is a programmer error, so previews must inject a sample.
  4. 4. What is the main testing benefit of putting a service behind a protocol and injecting it?

    The view depends on the protocol only, so any conforming type can stand in without changing the view.
  5. 5. Who must own an @Observable object that you distribute through the environment?

    The environment only passes the object down. Something has to create and keep it alive.

Summary

  • The environment is a set of values inherited down the view tree; modifiers override it for a subtree.
  • Read built-in values with @Environment(\.keyPath) and add your own with @Entry (or an EnvironmentKey in older code), always with a default.
  • Inject @Observable models with .environment(model) and read them with @Environment(Model.self); an ancestor must own the object.
  • Hide services behind protocols and inject different implementations for production, previews and tests.
  • Prefer initializer parameters for screen-specific data so dependencies stay visible.

Next: View Identity and Lifecycle, which explains when SwiftUI keeps your state and when it throws it away.