In SwiftUI, how does @AppStorage persist a setting such as a reader's font size, and which value types can it store?
answer
- a key in the preferences store
- fallback until the key is written
- projected value is a Binding
- 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 linesimport 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
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.
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.
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.
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.