skip to content

In SwiftUI, how do you add a custom environment value with the @Entry macro, and what did an EnvironmentKey conformance require before it?

level: middleimportance: should knowfreq 55%

answer

  1. extend EnvironmentValues
  2. the initial value is the default
  3. a key type and a subscript
  4. a modifier for the call site

basics

~20 s

Extend EnvironmentValues with a property marked @Entry and give it an initial value, which becomes the default. Before @Entry you wrote an EnvironmentKey with a static defaultValue plus a computed property that read and wrote self[Key.self].

solid answer

~40 s

A custom value is a new property on `EnvironmentValues`: `extension EnvironmentValues { @Entry var featureFlags = FeatureFlags() }`. The initial value is the default every view reads when no ancestor sets one. You read it with `@Environment(\.featureFlags)` and set it for a subtree with `.environment(\.featureFlags, flags)`, ideally wrapped in a small `View` extension so the call site reads like a built-in modifier. Before `@Entry` you wrote it by hand: a private type conforming to `EnvironmentKey` with a `static` `defaultValue`, then a computed property whose getter and setter used `self[FeatureFlagsKey.self]`. `@Entry` generates that key and those accessors. It arrived in the June 2024 SwiftUI release with the iOS 18 SDK, but it expands at compile time and its documentation lists iOS 13, so it works on older deployment targets.

code

swift · 24 lines
swift
import SwiftUI

struct FeatureFlags: Sendable {
    var newCheckout = false
    var showsRecommendations = true
}

extension EnvironmentValues {
    @Entry var featureFlags = FeatureFlags()
}

extension View {
    func featureFlags(_ flags: FeatureFlags) -> some View {
        environment(\.featureFlags, flags)
    }
}

struct CheckoutButton: View {
    @Environment(\.featureFlags) private var flags

    var body: some View {
        Button(flags.newCheckout ? "Pay now" : "Go to checkout") {}
    }
}

go deeper

for a junior

Recall that a custom value is a property added to EnvironmentValues, marked @Entry with an initial value, and read with @Environment and a key path.

for a middle

Explain what @Entry generates: an EnvironmentKey-style key holding the default and the accessors using self[Key.self], and why clients only ever see the key path.

for a senior

Discuss choosing a safe default, why the default is used silently, Sendable value types under Swift 6 checking, and the dedicated modifier for clean call sites.

for a principal

Be ready to set a team convention: which shared values deserve an environment entry, what their defaults must guarantee, and how hand-written keys get migrated.

## Why custom environment values exist SwiftUI's built-in **`EnvironmentValues`** carry what the framework knows about: color scheme, locale, the dismiss action. An app has context of its own that many screens need, such as **feature flags**, a theme or an analytics client. A custom environment value is simply a new property on `EnvironmentValues`, so it behaves exactly like the built-in ones: views inherit it from their container, `environment(_:_:)` overrides it for a subtree, and `@Environment` reads it. ## The @Entry macro The modern declaration is one line inside an extension: ```swift extension EnvironmentValues { @Entry var featureFlags = FeatureFlags() } ``` What you supply, and what each part does: - **An extension of `EnvironmentValues`.** The same macro also creates entries on `Transaction`, `ContainerValues` and `FocusedValues`; for `FocusedValues` the entry must be optional, because its default is always `nil`. - **An initial value.** It is the **default**: the value any view reads when no ancestor has set one. - **A type**, written or inferred from the initial value. A protocol-typed service needs the annotation: `@Entry var analytics: any AnalyticsClient = NoopAnalytics()`. The SDK declares `Entry()` as an attached **accessor** macro that also adds a **peer** declaration whose name starts with `__Key_`: together they stand in for the key type and the getter and setter you used to write by hand. ## Before @Entry: an EnvironmentKey by hand The older recipe, still valid and still seen in most codebases, takes three steps: 1. Declare a key type conforming to **`EnvironmentKey`** and give it the one requirement you must write, a `static` **`defaultValue`**. The compiler infers the key's associated `Value` type from it. 2. Extend `EnvironmentValues` with a computed property whose `get` returns `self[FeatureFlagsKey.self]` and whose `set` assigns `self[FeatureFlagsKey.self] = newValue`. 3. Optionally add a `View` extension that calls `environment(\.featureFlags, value)`. ```swift private struct FeatureFlagsKey: EnvironmentKey { static let defaultValue = FeatureFlags() } extension EnvironmentValues { var featureFlags: FeatureFlags { get { self[FeatureFlagsKey.self] } set { self[FeatureFlagsKey.self] = newValue } } } ``` Clients never touch the key type; they use the key path `\.featureFlags`, which is why the key is usually `private`. | | `@Entry` | `EnvironmentKey` by hand | |---|---|---| | Code per value | one property | a key type plus a computed property | | Where the default lives | the property's initial value | the key's `static defaultValue` | | Key type | generated and hidden | yours, usually `private` | | Reading and setting | `@Environment(\.featureFlags)`, `environment(_:_:)` | identical | ## A modifier for the call site Apple's documentation recommends pairing a custom value with a dedicated modifier, the way `lineLimit(_:)` pairs with `\.lineLimit`: ```swift extension View { func featureFlags(_ flags: FeatureFlags) -> some View { environment(\.featureFlags, flags) } } ``` The call site then reads `.featureFlags(betaFlags)`, and the key path becomes an implementation detail. ## Version and pitfalls - **Availability.** `@Entry` appeared in the June 2024 SwiftUI release alongside the iOS 18 SDK. The macro declaration in the iOS 27 SDK carries no `@available` restriction and its documentation page lists iOS 13, so a project building with that SDK or later can use it while still deploying to iOS 17. - **The default is silent.** A view whose ancestors never set the value reads the default without any error. Choose a default that is safe in previews and in a subtree that was never configured. - **Concurrency checking.** When you write the key by hand in the Swift 6 language mode, a `static` stored `defaultValue` of a type that is not `Sendable` can be reported as not concurrency-safe. Making small value types such as `FeatureFlags` conform to `Sendable` avoids it. - **Readers update with the value.** When an ancestor sets a new `FeatureFlags` value, SwiftUI updates the views that read `\.featureFlags`, exactly as it does for built-in values such as `colorScheme`. - **Value types read best.** A struct of flags changes as a whole value and every reader updates. A class can travel through a key path too (Apple's documentation injects one that way), but a change made inside the object is not a new environment value; a view sees it when the class is `@Observable` and `body` reads its properties, which is the subject of the lesson on Observation-based models. Knowing both forms matters in interviews: `@Entry` is what you write today, and `EnvironmentKey` is what you will read in an existing app and what the macro produces.

  • What does a view read from a custom @Entry value when no ancestor sets it, and why does that matter for previews?
    It reads the property's initial value, the default, with no error or warning. Previews and any subtree you forgot to configure therefore run against that default, so choose one that is harmless there, such as flags that keep new features off or a client that sends nothing.
  • Why do FocusedValues entries declared with @Entry have to be optional?
    Apple's documentation says the default for `FocusedValues` is always `nil`, so an entry cannot specify a different default and must have an optional type, as in `@Entry var selectedNote: Note?`. Environment, transaction and container entries can declare any default.

  • @Entry can only be used in apps whose deployment target is iOS 18
  • Custom environment values are optional and read as nil until someone injects them
  • A missing custom environment value crashes like a missing environment object
  • Views must use the EnvironmentKey type directly to read a custom value
  • @Entry is applied to a View extension to create a new modifier

Assumes the iOS 27 SDK; @Entry arrived with the June 2024 release (iOS 18 SDK) yet lists iOS 13 availability, so it deploys to iOS 17.