skip to content

Sources of Truth

Who owns each value and which change redraws which view: @State, bindings, Observation, the environment and the older object wrappers. The most asked SwiftUI area at every level.

on this pageshow

explore

questions

30

In SwiftUI, how does @AppStorage persist a setting such as a reader's font size, and which value types can it store?

level: juniorimportance: must knowfreq 55%

answer

  1. a key in the preferences store
  2. fallback until the key is written
  3. projected value is a Binding
  4. plist-friendly scalars, enums by raw value

basics

~20 s

@AppStorage binds a view property to a UserDefaults key: it reads the stored value or the declared default, writes on assignment and updates the view on change. It stores Bool, Int, Double, String, URL, Data, Date (iOS 18) and String- or Int-backed enums.

solid answer

~40 s

`@AppStorage("reader.fontSize") private var fontSize = 17.0` is a SwiftUI property wrapper that reflects a value in `UserDefaults.standard`, or in another store you pass with `store:`. Reading returns the stored value, or the declared default when nothing has been written under the key; assigning writes through, and SwiftUI invalidates the views that read it when that user default changes. Its projected value is a `Binding`, so `$fontSize` drives a `Slider` directly. For general values the SDK declares initializers only for `Bool`, `Int`, `Double`, `String`, `URL`, `Data`, their optionals, and `RawRepresentable` types with a `String` or `Int` raw value (plus a few SwiftUI customization types), so `enum Theme: String` works while a `Float`, an array or a `Codable` struct does not compile. `Date` support arrived in iOS 18.

code

swift · 26 lines
swift
import SwiftUI

enum ReaderTheme: String, CaseIterable, Identifiable {
    case system, light, sepia, dark
    var id: Self { self }
}

struct ReaderSettingsView: View {
    @AppStorage("reader.fontSize") private var fontSize = 17.0
    @AppStorage("reader.theme") private var theme: ReaderTheme = .system

    var body: some View {
        Form {
            Slider(value: $fontSize, in: 12...28, step: 1) {
                Text("Font size")
            }
            Picker("Theme", selection: $theme) {
                ForEach(ReaderTheme.allCases) { theme in
                    Text(theme.rawValue.capitalized).tag(theme)
                }
            }
            Text("The quick brown fox")
                .font(.system(size: fontSize))
        }
    }
}

go deeper

for a junior

Recall the shape: a string key, a default value, and a view that redraws when the value changes. Name the basic types it stores and show $value passed to a control.

for a middle

Explain that the default is only a fallback until the key is written, list the declared types including RawRepresentable enums, and say what you do for a type with no initializer.

for a senior

Show production judgment: one shared definition per key and default, String raw values for persisted enums, Date only from iOS 18, and clearing user-specific keys on sign-out.

for a principal

Frame @AppStorage as the preferences layer of a persistence policy: small settings here, secrets in the Keychain, user data in a database, and key naming the whole team follows.

## What @AppStorage is `@AppStorage` is a SwiftUI property wrapper that **reflects a value from `UserDefaults`** and invalidates the view when that value changes. You declare it as a stored property of a view, give it a **key** (a string) and usually a **default value**, and SwiftUI does the reading, the writing and the redrawing. It has existed since iOS 14, so any app with an iOS 17 deployment target can use it. ```swift @AppStorage("reader.fontSize") private var fontSize = 17.0 ``` `UserDefaults` is the system's per-app **preferences store**: a key-value store meant for small settings such as a font size, a theme, or whether onboarding has been shown. `@AppStorage` is SwiftUI's declarative front door to it, so a reading app can remember the reader's font size and theme across launches without any save or load code. ## Reading, writing and redrawing - **Reading** the property returns the value stored under the key. If nothing has ever been written under that key, it returns the default from the declaration. - **Writing** (`fontSize = 20`) stores the new value under the key. - **Redrawing**: Apple's documentation says the wrapper "invalidates a view on a change in value in that user default", so views that read the property update when the value changes, including a write made through `UserDefaults` itself on the same store and key. - **The projected value** `$fontSize` is a `Binding<Double>`, so you can pass it to a `Slider`, `Toggle`, `Picker` or a child view that takes a `@Binding`. - **The store** is `UserDefaults.standard` unless you pass `store:` or an ancestor applies `defaultAppStorage(_:)`. Because the declared default is only a fallback, two views that declare the same key with **different defaults** can show different values until one of them writes. Declare each key and its default once, in a shared place, and refer to it from every view. ## The value types the SDK accepts `@AppStorage` is not generic over "anything storable". The SDK declares one initializer per supported type, and the compiler picks among them: | Value type | Available since | Note | |---|---|---| | `Bool`, `Int`, `Double`, `String` | iOS 14 | The everyday settings | | `URL`, `Data` | iOS 14 | `Data` is the escape hatch for values you encode yourself | | `RawRepresentable` with an `Int` or `String` raw value | iOS 14 | Enums such as `enum Theme: String` | | Optionals of the plain types above | iOS 14 | Declared without a default; `nil` while the key is unset | | Optional `RawRepresentable` | iOS 15 | `Theme?` | | `Date` and `Date?` | iOS 18 | Needs an availability check on an iOS 17 target | | `TableColumnCustomization`, `TabViewCustomization`, `ToolbarLabelStyle` | iOS 17 to 18 | SwiftUI's own types for persisting a person's table, tab and toolbar customizations | What is **not** on the list matters as much. A `Float`, a `CGFloat`, an array, a dictionary or a `Codable` struct has no matching initializer, so the declaration fails to compile rather than failing at run time. ## Storing an enum or a custom value 1. For a fixed set of choices, make the type an enum with a `String` (or `Int`) raw value. `@AppStorage` stores the raw value and rebuilds the case when it reads. 2. For a small structured value, encode it to `Data` yourself, for example with `JSONEncoder`, and decode it where you read it. 3. For anything that grows, such as a list of saved articles or downloaded content, stop: that is not a preference, and it belongs in a database or a file. Prefer **`String` raw values** for persisted enums. With implicit `Int` raw values, inserting a case in the middle renumbers the cases after it, and every value already stored on users' devices silently changes meaning. With implicit `String` raw values, renaming a case changes its raw value, and devices still holding the old one fall back to the default; give persisted cases explicit raw values, or migrate. ## Where it fits and where it does not - It is designed as a **view's stored property**. It conforms to `DynamicProperty`, and SwiftUI updates such properties before recomputing the body of the view that holds them. - It is a **preferences store, not a secure one**: credentials belong in the Keychain. - It is **app-wide**: every window reads the same value. A value that should differ per window, such as which article each iPad window shows, belongs in `@SceneStorage`. - It keeps its value across launches until the app removes the key or the app is deleted, so user-specific settings need clearing when a different person signs in. In an interview, the strong answer names the key-plus-default model, the `Binding` projection, the invalidation on change and the closed list of types, and then says what you do for a type that is not on the list.

  • What happens when two SwiftUI views declare @AppStorage with the same key but different default values?
    Both read the same key in the same store. Until something writes that key, each view falls back to its own declared default, so the two screens can disagree. As soon as one writes, both show the stored value. Teams avoid this by declaring each key and its default once, in a shared constants type, and using it everywhere.
  • Can you put @AppStorage on a property of an @Observable model class?
    Not as a tracked property. The `@Observable` macro gives each tracked stored property accessors, and Swift does not allow a property wrapper on a computed property, so it fails to compile. Marking it `@ObservationIgnored` compiles but loses change tracking. Models usually read and write `UserDefaults` directly and keep a tracked copy, or the view keeps the `@AppStorage`.
  • How do you persist a small Codable value, such as a reading position, with @AppStorage?
    Encode it to `Data` with `JSONEncoder`, store the `Data` under a key, and decode it when you read. `Data` is one of the declared types, so it compiles, but you own the encoding, the error handling and any format migration. Keep it small: once it grows into a collection, it belongs in a database or a file.

  • @AppStorage can store any Codable struct or array directly.
  • The declared default overwrites the stored value on every launch.
  • A Float or CGFloat property works with @AppStorage just like Double.
  • Views using @AppStorage never notice a write made through UserDefaults directly.
  • @AppStorage is secure storage, fine for passwords and tokens.

Assumes the iOS 27 SDK; @AppStorage gained Date and Date? in iOS 18, while its core types date from iOS 14 and optional RawRepresentable values from iOS 15.

open as a page

In SwiftUI, how do you read a system environment value such as colorScheme or dismiss with @Environment, and where does that value come from?

level: juniorimportance: must knowfreq 68%

basics

~20 s

Declare a property such as @Environment(.colorScheme) var colorScheme, naming a key path into EnvironmentValues. The value is inherited from the view's ancestors; SwiftUI fills many values from system settings and updates views that read them when they change.

open as a page

In SwiftUI, how does a child view edit a value its parent owns in @State, and what does the $ prefix give you?

level: juniorimportance: must knowfreq 80%

basics

~20 s

The child declares a @Binding property and the parent passes $value, the state's projectedValue, which is a Binding: a read-write reference to the parent's storage with no storage of its own, so the child's writes update the parent's state.

open as a page

In SwiftUI, why does a view use @State for a value it changes, instead of a plain var stored property on the view struct?

level: juniorimportance: must knowfreq 85%

basics

~20 s

A SwiftUI view is a short-lived struct whose body cannot mutate it. @State keeps the value in storage SwiftUI manages outside the struct, so writes survive the struct being recreated and update the views that read the value.

open as a page

In SwiftUI, what does marking a model class with the @Observable macro give you, and when do you add @ObservationIgnored to a property?

level: juniorimportance: must knowfreq 72%

basics

~20 s

The @Observable macro from Apple's Observation framework makes a class's stored var properties observable with no @Published, so a SwiftUI view that reads one redraws when it changes. @ObservationIgnored opts out a property that no view displays.

open as a page

In SwiftUI on iOS 17 and later, how do you declare a view model for a hotel search screen, and why mark it @MainActor?

level: middleimportance: must knowfreq 68%

basics

~20 s

Declare a final class with Observation's @Observable macro and @MainActor, holding the screen's state and intent methods. SwiftUI tracks the properties body reads, and main-actor isolation keeps every mutation on the actor body runs on.

open as a page

In SwiftUI, why does a feed view model declared with @ObservedObject reset whenever the parent tab redraws, and how does @StateObject fix it?

level: middleimportance: must knowfreq 80%

basics

~20 s

@ObservedObject does not own its object, so a default value like FeedViewModel() runs again whenever the parent rebuilds the view struct. @StateObject owns it: SwiftUI creates the model once per view identity and keeps it across redraws.

open as a page

In SwiftUI, how do you pass a TextField a binding to a property of an @Observable model, including one read from @Environment?

level: middleimportance: must knowfreq 68%

basics

~10 s

Mark the model @Bindable and pass $model.property, as in $cart.couponCode. For a model read with @Environment, which offers no binding, declare @Bindable var cart = cart inside body and bind from that local.

open as a page

In SwiftUI, when an @Observable cart model changes, how does SwiftUI decide which views redraw, and what counts as a tracked read?

level: middleimportance: must knowfreq 76%

basics

~20 s

SwiftUI records which observable properties each view's body reads while it runs, and when one of them changes it updates only the views that read it. Reads outside body, such as in a Button action, subscribe nothing.

open as a page

In SwiftUI, a cart screen stores its @Observable model as a plain property initialized inline and loses the items whenever its parent redraws; why, and how should the model be owned and shared?

level: seniorimportance: must knowfreq 62%

basics

~20 s

A plain property initialized inline is re-created every time the parent rebuilds the view, so a fresh empty CartModel replaces the old one. Own the model with @State where it is created, pass it down, or place it with environment(_:).

open as a page

In SwiftUI, how does an ObservableObject class with @Published properties cause views to update, and what does objectWillChange signal?

level: juniorimportance: should knowfreq 58%

basics

~10 s

Setting a @Published property makes the object's objectWillChange publisher emit before the value changes; SwiftUI invalidates every view holding the object in @StateObject, @ObservedObject or @EnvironmentObject and re-runs their bodies, whichever property they read.

open as a page

In SwiftUI with Observation, when is a per-screen view model overhead, and what does the model-view approach with environment models do instead?

level: middleimportance: should knowfreq 52%

basics

~20 s

A per-screen view model is overhead when it only copies or forwards an observable model's properties. In the model-view approach, shared @Observable models live in the environment, views read them directly with tracked reads, and logic sits in model methods.

open as a page

In SwiftUI, how do you make @AppStorage use an App Group's UserDefaults suite so an extension sees the same settings?

level: middleimportance: should knowfreq 28%

basics

~10 s

Create the suite with UserDefaults(suiteName:) using an App Group both targets join, then pass it as @AppStorage's store: argument or apply defaultAppStorage(_:) to a scene or view so every @AppStorage inside uses it.

open as a page

In SwiftUI, when do you use @SceneStorage instead of @AppStorage, for example to reopen the article each iPad window was showing?

level: middleimportance: should knowfreq 40%

basics

~20 s

@AppStorage holds one app-wide value per UserDefaults key, right for preferences like a theme. @SceneStorage holds a per-scene value the system saves and restores, right for UI state like the article an iPad window shows; destroying that scene discards it.

open as a page

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%

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].

open as a page

In SwiftUI, how does environment(_:_:) scope a value to one subtree, and which value does a view read when several ancestors set the same key?

level: middleimportance: should knowfreq 42%

basics

~20 s

environment(::) sets a value for the modified view and its descendants only, until a deeper environment modifier sets it again; the nearest ancestor wins. transformEnvironment(:transform:) instead edits the inherited value, which is how disabled(:) combines with outer settings.

open as a page

In SwiftUI, when do you create a binding with Binding(get:set:) or Binding.constant(_:) instead of passing a $ projection?

level: middleimportance: should knowfreq 40%

basics

~20 s

Binding(get:set:) adapts a source of truth whose stored shape differs from what a control needs, such as minutes over state kept in seconds. Binding.constant(_:) fills a binding parameter with a fixed value that ignores writes, typically in previews.

open as a page

In a SwiftUI checkout screen built as a unidirectional store on Observation, why does every view re-run body on each action, and how do you narrow it?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Observation tracks the store's stored properties, so a single state struct is one tracked key path: any action that mutates any field notifies every view that read any part of it. Split state into separate stored properties or scoped child stores.

open as a page

A SwiftUI hotel results screen needs a view model whose search service differs in previews and per subtree; where should the screen build that view model, and how does it get the service?

level: seniorimportance: should knowfreq 42%

basics

~20 s

Build the view model where the chosen service is actually available: in the screen's task, held in optional @State, or in a parent or feature entry that picks the service and passes the model in. Either way the model takes the service through its own initializer as a protocol type.

open as a page

Reviewing a SwiftUI pull request that keeps an auth token in @AppStorage and a whole article list in @SceneStorage, what do you flag and where should each go?

level: seniorimportance: should knowfreq 38%

basics

~20 s

Both are misuse. @AppStorage is a UserDefaults preference without Keychain protection, so the token belongs in the Keychain. @SceneStorage is for lightweight per-scene UI state, so keep only the open article's ID there and the list in a database or files.

open as a page

In SwiftUI, why does an @Environment property read in a view's initializer, or declared inside a view model class, return the default value and never update?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Environment is a dynamic property that SwiftUI fills only when the property is installed on a view, just before body. In an initializer, or in a class SwiftUI never installs, the getter logs a runtime fault and returns the key's default.

open as a page

When injecting an analytics client and a feature-flag service into SwiftUI views, when do you choose the environment over initializer parameters, and what does each cost?

level: seniorimportance: should knowfreq 45%

basics

~20 s

Use the environment for cross-cutting services many descendants read, such as analytics and feature flags; use initializer parameters for a view's required inputs. The environment avoids forwarding and swaps easily in previews, but hides the dependency and silently falls back to the default.

open as a page

In SwiftUI, a focus timer's DurationPicker seeds its @State from a preset parameter in init; why does it keep showing the first preset after the parent passes a new one?

level: seniorimportance: should knowfreq 60%

basics

~20 s

SwiftUI keeps @State storage for as long as the view keeps its identity and applies an initial value only when it first creates that storage. Later inits that pass a new preset are ignored, so the picker keeps editing its own stale copy.

open as a page

In SwiftUI, why does a view using @EnvironmentObject crash at runtime when no ancestor injected the object, and how do you prevent it?

level: seniorimportance: should knowfreq 50%

basics

~20 s

@EnvironmentObject finds its object by type in values an ancestor set with environmentObject(_:); the compiler cannot check that, and reading the property with nothing injected is a fatal runtime error. Inject at the scene root and in every preview.

open as a page

In SwiftUI, why does a @StateObject initialized from a view parameter with StateObject(wrappedValue:) ignore later changes to that parameter, and how do you reset it?

level: seniorimportance: should knowfreq 45%

basics

~20 s

StateObject(wrappedValue:) takes an autoclosure that SwiftUI runs only the first time for a view's identity, so later parameter values never build a model. Reset by changing identity with id(_:) or keep the model and update it.

open as a page

Outside SwiftUI views, how do you react to changes in an @Observable model with withObservationTracking or the Observations sequence, and what catches people out?

level: seniorimportance: should knowfreq 30%

basics

~20 s

withObservationTracking(_:onChange:) runs a closure, records the observable properties it reads, and calls onChange once, before the first of them changes; you must re-register to keep watching. On iOS 26 and later, Observations wraps this as an async sequence.

open as a page

Three developers building a SwiftUI hotel-booking feature favour @Observable view models, shared environment models or a unidirectional store; how do you set the team's standard?

level: principalimportance: should knowfreq 40%

basics

~20 s

Pick one default per kind of screen from the app's constraints: shared @Observable models for display and editing, @MainActor view models where a screen owns transient state, and a store only for flows whose effects need one writer. Write it down with exceptions.

open as a page

Your SwiftUI news app still supports iOS 16 and uses ObservableObject view models everywhere; how would you decide on and sequence a migration to @Observable?

level: principalimportance: should knowfreq 42%

basics

~20 s

Observation requires iOS 17, so raising the deployment target is the first decision. Then migrate one model type at a time, updating every wrapper site, and plan for State initialization, lost publishers and changed update behaviour.

open as a page

A tester reports that SwiftUI's @SceneStorage never restores the open article after relaunch; how do you diagnose it and test scene restoration properly on iOS?

level: seniorimportance: nice to knowfreq 20%

basics

~20 s

Check how the app was ended: force-quitting from the app switcher discards preserved state, and destroying a scene destroys its @SceneStorage. Test by backgrounding the app, then stopping it from Xcode and relaunching; the system never guarantees when values are saved.

open as a page

In SwiftUI built with Xcode 27, how does the State() macro change when a class-typed @State default value, such as a timer engine, is created?

level: seniorimportance: nice to knowfreq 30%

basics

~20 s

Built with Xcode 26 or earlier, the @State property wrapper evaluates its default value every time SwiftUI initializes the view and keeps only the first. Built with Xcode 27, the State() macro creates a class-typed default once, the first time.

open as a page