Custom environment values with @Entry

SwiftUI Mid-level Swift 6.0+ iOS 17+ Reviewed By Alok Singh

Pick the fix

You need a custom accent environment value with a default of .blue. Which is the shortest correct code?

Options
Hint 1 of 1

Which macro arrived with Xcode 16?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A extension EnvironmentValues { @Entry var accent: Color = .blue }

Correct. @Entry generates the key and accessors.

Why not the others?
  • B A struct AccentKey: EnvironmentKey plus a computed property. Still valid, but it is the old, longer way that @Entry replaces.
  • C @Environment var accent: Color = .blue in each view. @Environment needs a key path or type to read from.
  • D static var accent = Color.blue on a global type. A global isn't scoped to a subtree and can't be overridden per view.

30-second answer

Environment values flow down the view tree. Since Xcode 16 you declare one with @Entry inside extension EnvironmentValues, which generates the key and accessors for you. Set it with .environment(\.accent, .red) and read it with @Environment(\.accent). Before @Entry you wrote an EnvironmentKey type by hand.

Practise saying it · 30 s. No recording, just a timer

Explain custom environment values.

Say your answer out loud, then check which of these points you covered:

  • Values flow down
  • @Entry generates the key
  • Preferences flow up

Deep dive

@Entry is a macro, so it back-deploys to older iOS versions when built with Xcode 16 or later.

It also works for FocusedValues, Transaction and ContainerValues.

Use the environment for configuration (theme, locale, feature flags), and .environment(model) for @Observable models.

Preferences (PreferenceKey) send values up the tree; the environment sends them down.

Common mistakes

  • Writing EnvironmentKey boilerplate in new code.
  • Using the environment for data that one child needs.
  • Forgetting to inject a required environment model in previews.

Senior take & follow-ups

Seniors know both directions (environment down, preferences up) and use @Entry in new code.

Follow-up questions

Think of your answer first, then open the hint.

  1. How do values flow up the tree?

    Show hint

    PreferenceKey with onPreferenceChange.

  2. What is the default value used for?

    Show hint

    Any view outside an override.

Suggest a fix if something here is wrong or out of date.