ViewLab

Swift & SwiftUI course › Session 4

State, bindings, controls and forms

Where a SwiftUI screen keeps its data, how a child view edits its parent's data, every common input control, and forms that validate, move focus and remember settings.

About 30 minutes · covers @State, @Binding, controls, Form, @FocusState, @AppStorage

Open the interactive lesson (live previews, quizzes) →

What you'll learn

Contents

  1. Why views need state
  2. @State
  3. @Binding and the $ projected value
  4. Custom Binding(get:set:)
  5. Controls
  6. Picker tags, number formatting and control styles
  7. Form, Section and disabled()
  8. @FocusState and the keyboard
  9. onSubmit: add, clear and move focus
  10. @AppStorage and @SceneStorage

Why views need state

A SwiftUI view is a struct: a cheap description of the screen, not the screen itself. SwiftUI calls body to get that description, and calls it again whenever data the view reads changes. This is declarative UI: you describe the screen for the current data; SwiftUI works out what changed on screen.

body is a non-mutating computed property, so it can't change the view's own stored properties. That is exactly the rule plain Swift applies to any struct method that isn't mutating.

This doesn't compile
struct Profile {
    var name = ""
}
let profile = Profile()
profile.name = "Asha"

A let struct value is immutable, and so is self inside body. A view needs storage that lives outside the struct: that is what @State gives it.

Doesn't compile: the button's action can't mutate the view struct.
struct CounterView: View {
    var count = 0                 // plain stored property

    var body: some View {
        Button("Tapped \(count) times") {
            count += 1            // error: 'self' is immutable
        }
    }
}

Try “Why views need state” with live code →

@State

@State is a property wrapper. SwiftUI stores the value outside the view struct and keeps it alive while the view stays on screen. Changing it makes SwiftUI recompute body.

The view owns count. Tapping a button changes it; SwiftUI redraws the Text.
struct CounterView: View {
    @State private var count = 0

    var body: some View {
        VStack(spacing: 12) {
            Text("Count: \(count)")
                .font(.largeTitle)
            Button("Add one") { count += 1 }
            Button("Reset", role: .destructive) { count = 0 }
        }
    }
}

@State works best with value types because changing any property of a struct produces a new value of the whole struct. Swift reports that as a change to the @State property itself, so SwiftUI notices it. And because structs are copied, no other code can change the value behind the view's back.

struct Settings: Equatable {
    var username = "Asha"
    var notifications = true
}

var settings = Settings()
let before = settings              // a copy, not a reference
settings.notifications = false     // change one property...
print(before == settings)          // ...and the whole value is different
print(before.notifications, settings.notifications)

var copy = settings
copy.username = "Meera"
print(settings.username, copy.username)

Output

false
true false
Asha Meera

Try “@State” with live code →

@Binding and the $ projected value

A binding is a two-way connection to data owned somewhere else. It doesn't store the value; it can read and write it. @Binding lets a child view edit its parent's state.

Writing $ before a @State property gives its projected value: a Binding. count is the Int; $count is a Binding<Int>.

The parent owns volume. The child reads and writes it through the binding.
struct VolumeView: View {
    @State private var volume = 5.0          // source of truth

    var body: some View {
        VStack {
            Text("Volume: \(Int(volume))")
            VolumeSlider(volume: $volume)    // pass a binding with $
        }
    }
}

struct VolumeSlider: View {
    @Binding var volume: Double              // no initial value, not private

    var body: some View {
        Slider(value: $volume, in: 0...10)   // a binding can be passed on with $
    }
}

#Preview {
    VolumeSlider(volume: .constant(7))      // a binding that never changes
}

Behind the scenes a binding is just a getter and a setter. This plain-Swift model shows the idea:

struct MyBinding<Value> {
    let get: () -> Value
    let set: (Value) -> Void
}

var volume = 5          // the source of truth
let binding = MyBinding(get: { volume }, set: { volume = $0 })

binding.set(binding.get() + 2)    // the "child" edits through the binding
print(volume)
volume = 1                         // the owner changes it
print(binding.get())

Output

7
1
@State@Binding
Owns the data?Yes: it is the source of truthNo: refers to someone else's
Initial valueRequired (= 0)None; passed in by the parent
AccessprivateSet by the parent's initializer
How you pass itChildView(value: $value)Pass on again with $value
PreviewWorks as isUse .constant(...)
What does this print?
struct Child {
    var count: Int          // a plain property: the child gets a copy
}
var parentCount = 3
var child = Child(count: parentCount)
child.count += 1
print(parentCount, child.count)
Show the answer
3 4

That is what happens if you pass count instead of $count: the child edits its own copy and the parent never sees the change.

Try “@Binding and the $ projected value” with live code →

Custom Binding(get:set:)

Sometimes a control needs a binding to a value you don't store directly. Binding(get:set:) builds one from two closures: get computes the value the control shows, and set decides what to change when the user edits it.

Syntax: the result is a Binding<Value> you can pass anywhere a $ binding goes.
Binding(
    get: { /* return the value the control should show */ },
    set: { newValue in /* update your real state */ }
)

Example: one selected item out of many

A list of study rooms, each with a Toggle, where only one room can be booked at a time. There is no Bool per room to bind to. The real state is one optional id; each toggle gets a binding that asks "is this the booked room?".

Turning on Room 204 turns Room 101 off: both toggles read the same bookedID.
struct Room: Identifiable {
    let id: String          // "Room 101"
    let seats: Int
}

struct RoomBookingView: View {
    let rooms = [Room(id: "Room 101", seats: 4),
                 Room(id: "Room 204", seats: 8),
                 Room(id: "Quiet zone", seats: 1)]

    @State private var bookedID: String? = nil      // the single source of truth

    var body: some View {
        List(rooms) { room in
            Toggle("\(room.id) (\(room.seats) seats)", isOn: isBooked(room))
        }
    }

    private func isBooked(_ room: Room) -> Binding<Bool> {
        Binding(
            get: { bookedID == room.id },
            set: { isOn in
                if isOn {
                    bookedID = room.id                  // turning one on turns the others off
                } else if bookedID == room.id {
                    bookedID = nil                      // only the booked room can clear it
                }
            }
        )
    }
}

The same idea in plain Swift, with closures standing in for the binding:

struct MyBinding<Value> {
    let get: () -> Value
    let set: (Value) -> Void
}

var bookedID: String? = nil
func isBooked(_ id: String) -> MyBinding<Bool> {
    MyBinding(get: { bookedID == id },
              set: { isOn in
                  if isOn { bookedID = id }
                  else if bookedID == id { bookedID = nil }
              })
}

let rooms = ["Room 101", "Room 204", "Quiet zone"]
isBooked("Room 204").set(true)
for room in rooms { print(room, isBooked(room).get()) }
isBooked("Quiet zone").set(true)
print(bookedID ?? "none")
isBooked("Room 101").set(false)    // not the booked room: no change
print(bookedID ?? "none")
isBooked("Quiet zone").set(false)
print(bookedID ?? "none")

Output

Room 101 false
Room 204 true
Quiet zone false
Quiet zone
Quiet zone
none
$stateBinding(get:set:)
Where the value livesExactly in that propertyAnywhere; computed in get
What a write doesStores the new valueWhatever your set closure does
Typical useMost controlsDerived values: "is this the selected one", unit conversion, clamping

One open at a time: an accordion

DisclosureGroup(_:isExpanded:) takes a Binding<Bool>. If every row binds to the same @State var isExpanded, every row opens together. Store which row is open instead, and build a binding per row:

Opening Tuesday closes Monday, because there is only one openDay.
struct TimetableView: View {
    let days = ["Monday", "Tuesday", "Wednesday"]
    @State private var openDay: String? = nil

    var body: some View {
        List(days, id: \.self) { day in
            DisclosureGroup(day, isExpanded: Binding(
                get: { openDay == day },
                set: { openDay = $0 ? day : nil }
            )) {
                Text("Lectures for \(day)")
            }
        }
    }
}
In TimetableView, you replace the custom binding with isExpanded: $allOpen, where @State private var allOpen = false. What happens when you tap Monday?
Show the answer

All three days open, because all three groups are bound to the same Bool. Tapping any of them closes them all. Per-row expansion needs per-row state: an optional id (one open), a Set of ids (several open), or a custom binding like above.

Try “Custom Binding(get:set:)” with live code →

Controls

Button

A role describes meaning (red for destructive). A style describes looks.
Button("Save") { save() }

Button(role: .destructive) {
    deleteAccount()
} label: {
    Label("Delete account", systemImage: "trash")
}

Button("Cancel", role: .cancel) { }

Button("Continue") { next() }
    .buttonStyle(.borderedProminent)   // also .bordered, .borderless, .plain
    .controlSize(.large)

TextField and SecureField

text: binds a String. value:format: binds a number or other value.
@State private var email = ""
@State private var password = ""
@State private var age = 18

TextField("Email", text: $email, prompt: Text("name@college.edu"))
    .keyboardType(.emailAddress)
    .textInputAutocapitalization(.never)
    .autocorrectionDisabled()
    .submitLabel(.next)
    .onSubmit { print("Return pressed") }

SecureField("Password", text: $password)   // shows dots

TextField("Age", value: $age, format: .number)
    .keyboardType(.numberPad)

Toggle, Slider, Stepper

Slider needs a floating-point binding (Double). Stepper works with Int.
@State private var wifiOn = true
@State private var brightness = 0.5
@State private var guests = 2

Toggle("Wi-Fi", isOn: $wifiOn)

Slider(value: $brightness, in: 0...1, step: 0.1) {
    Text("Brightness")
} minimumValueLabel: {
    Image(systemName: "sun.min")
} maximumValueLabel: {
    Image(systemName: "sun.max")
}

Stepper("Guests: \(guests)", value: $guests, in: 1...10, step: 1)
This doesn't compile
let guests = 4                  // an Int, like a Stepper's value
let sliderValue: Double = guests

Swift never converts Int to Double for you. That's why a Slider can't bind to an Int state: convert with Double(guests) or store a Double.

A Stepper with in: never goes past the range: the + or − button just stops working at the edge. The logic is a clamp:

func clamp(_ value: Int, to range: ClosedRange<Int>) -> Int {
    min(max(value, range.lowerBound), range.upperBound)
}

func step(_ value: Int, by amount: Int, in range: ClosedRange<Int>) -> Int {
    clamp(value + amount, to: range)
}

var guests = 9
guests = step(guests, by: 1, in: 1...10)
print(guests)
guests = step(guests, by: 1, in: 1...10)
print(guests)
print(step(2, by: -5, in: 1...10))

Output

10
10
1

Picker

The selection binding and every tag must have exactly the same type.
enum Theme: String, CaseIterable, Identifiable {
    case light = "Light", dark = "Dark", system = "System"
    var id: Self { self }
}

@State private var theme: Theme = .system

Picker("Theme", selection: $theme) {
    ForEach(Theme.allCases) { option in
        Text(option.rawValue).tag(option)
    }
}
.pickerStyle(.segmented)   // .menu, .segmented, .wheel, .inline, .navigationLink
Picker styleLooks likeGood for
.menuA button that opens a pop-up menu (the default in a Form on iOS 16+)Many options, little space
.segmentedA row of segments2–5 short options
.wheelA spinning wheelScrolling through values
.inlineOptions listed in place with a checkmarkSettings lists
.navigationLinkA row that pushes a list of options (iOS 16+, needs a NavigationStack)Long lists in a Form

Enums are the natural model for pickers. CaseIterable gives allCases; Identifiable lets ForEach use them directly.

enum Theme: String, CaseIterable, Identifiable {
    case light = "Light", dark = "Dark", system = "System"
    var id: Self { self }
}

print(Theme.allCases.map { $0.rawValue })
print(Theme(rawValue: "Dark") == .dark)
print(Theme(rawValue: "Blue") == nil)
print(Theme.allCases.count)

Output

["Light", "Dark", "System"]
true
true
3

DatePicker and ColorPicker

in: takes a range of dates; one-sided ranges are common.
@State private var birthday = Date.now
@State private var reminder = Date.now
@State private var accent = Color.blue

DatePicker("Birthday", selection: $birthday,
           in: ...Date.now,                 // no future dates
           displayedComponents: .date)

DatePicker("Reminder", selection: $reminder,
           in: Date.now...,                 // no past times
           displayedComponents: [.date, .hourAndMinute])
    .datePickerStyle(.graphical)            // also .compact, .wheel

ColorPicker("Accent colour", selection: $accent, supportsOpacity: false)
ControlBinding typeKey parameters
TextFieldString (or a value with format:)prompt:, axis: .vertical for multi-line
SecureFieldStringHides the text
ToggleBoolisOn:
SliderDouble (floating point)in:, step:
StepperInt (any Strideable)in:, step:
PickerAny Hashable typeselection:, .tag()
DatePickerDatein:, displayedComponents:
ColorPickerColorsupportsOpacity:

Try “Controls” with live code →

Picker tags, number formatting and control styles

Implicit tags from ForEach

If the options inside a Picker come from ForEach and you don't write .tag(...), SwiftUI uses each element's id as its tag. With ForEach(cities, id: \.self) over a [String], the tags are the strings themselves, so the selection must be a String.

No .tag needed: the ForEach id becomes the tag.
struct CityPicker: View {
    let cities = ["Dehradun", "Shimla", "Pune"]
    @State private var city = "Dehradun"           // String, same type as the implicit tags

    var body: some View {
        Form {
            Picker("City", selection: $city) {
                ForEach(cities, id: \.self) { name in
                    Text(name)                       // implicit tag: name (a String)
                }
            }
            Text("Selected: \(city)")
        }
    }
}
Selection typeOptionsWorks?
StringForEach(cities, id: \.self) (tags are String)Yes
Int (an index)ForEach(cities, id: \.self)No: tags are String, nothing is selected
Int (an index)ForEach(cities.indices, id: \.self) with Text(cities[i])Yes: tags are Int
String?ForEach(cities, id: \.self)No: tags are String, not String?; add .tag(Optional(name))
An enumForEach(Theme.allCases) with Identifiable and id: SelfYes: the id is the case itself
The selection is @State private var cityIndex = 0 (an Int), and the options are ForEach(cities, id: \.self) { Text($0) }. What does the Picker show, and what happens when you choose "Pune"?
Show the answer

It compiles and runs, but no option is shown as selected, and choosing Pune doesn't change cityIndex: no tag is an Int, so nothing ever matches. Xcode may also log a warning about a selection with no matching tag. Fix by making the selection a String, or by looping over cities.indices.

Showing numbers in Text

Two ways to round a Double in a Text. The old way is a C-style format specifier inside the interpolation; the current way is a format style, which also knows about locales, currencies and percentages.

specifier: only works inside Text interpolation; format styles work in Text, TextField and LabeledContent.
let rating = 4.36
let fee = 1250.5

Text("\(rating, specifier: "%.1f")")                             // 4.4  (old style, still works)
Text(rating, format: .number.precision(.fractionLength(1)))      // 4.4  (format style, iOS 15+)
Text(fee, format: .currency(code: "INR"))                        // e.g. ₹1,250.50, laid out for the user's locale
Text(0.82, format: .percent)                                     // e.g. 82%
Text("Rating: \(rating, format: .number.precision(.fractionLength(1)))")   // inside a sentence
specifier: "%.1f"format: .number.precision(...)
Kindprintf-style stringType-checked FormatStyle
TyposA wrong string still compiles and shows odd outputA wrong name is a compile error
Currency, percent, localeBy handBuilt in: .currency(code:), .percent
Two-way editingNoYes: TextField("Fee", value: $fee, format: .currency(code: "INR"))

Text field and button styles

Styles change how a control looks, never what it does.
TextField("Your name", text: $name)
    .textFieldStyle(.roundedBorder)       // a visible box; useful outside a Form

Button("Book") { book() }
    .buttonStyle(.borderedProminent)      // filled with the tint colour: the main action

Button("Details") { showDetails() }
    .buttonStyle(.bordered)               // light tinted background: secondary actions

Button("Skip") { skip() }
    .buttonStyle(.plain)                  // no button styling at all, just the label

VStack {
    TextField("Email", text: $email)
    SecureField("Password", text: $password)
}
.textFieldStyle(.roundedBorder)           // set on a container: applies to every field inside

Try “Picker tags, number formatting and control styles” with live code →

Form, Section and disabled()

Form is a container for data entry. On iOS it looks like the Settings app: a grouped, scrolling list where each control gets a row. Section groups rows and can have a header and a footer.

Section("Title") is a header shortcut. Use header: and footer: closures for both.
struct SettingsView: View {
    @State private var username = ""
    @State private var notifications = true
    @State private var volume = 0.5

    var body: some View {
        NavigationStack {
            Form {
                Section("Account") {                  // header only
                    TextField("Username", text: $username)
                }
                Section {
                    Toggle("Notifications", isOn: $notifications)
                    Slider(value: $volume, in: 0...1)
                        .disabled(!notifications)     // greyed out when off
                } header: {
                    Text("Sound")
                } footer: {
                    Text("Volume only applies when notifications are on.")
                }
                Section {
                    Button("Save") { save() }
                        .disabled(username.isEmpty)
                }
            }
            .navigationTitle("Settings")
        }
    }

    private func save() { print("Saved", username) }
}

Validation is ordinary Swift. Return a list of problems; the form is valid when the list is empty.

func problems(name: String, email: String, password: String) -> [String] {
    var list: [String] = []
    if name.allSatisfy({ $0.isWhitespace }) { list.append("Name is required") }
    if !email.contains("@") || !email.contains(".") { list.append("Email looks wrong") }
    if password.count < 8 { list.append("Password needs 8+ characters") }
    if !password.contains(where: { $0.isNumber }) { list.append("Password needs a digit") }
    return list
}

print(problems(name: "  ", email: "asha", password: "secret"))
print(problems(name: "Asha", email: "asha@gehu.ac.in", password: "swift2026"))
let canSubmit = problems(name: "Ravi", email: "ravi@x.in", password: "short1").isEmpty
print("Button enabled:", canSubmit)

Output

["Name is required", "Email looks wrong", "Password needs 8+ characters", "Password needs a digit"]
[]
Button enabled: false

Derived values (totals, averages, error lists) should be computed from state, not stored in another @State. Here is the maths behind the Tip calculator project:

func split(bill: Double, percent: Int, people: Int) -> (tip: Double, total: Double, each: Double) {
    let count = max(people, 1)                 // never divide by zero
    let tip = bill * Double(percent) / 100
    let total = bill + tip
    return (tip, total, total / Double(count))
}

let a = split(bill: 1200, percent: 15, people: 4)
print(a.tip, a.total, a.each)
let b = split(bill: 1000, percent: 10, people: 3)
print(b.total, b.each)
print(split(bill: 500, percent: 0, people: 0).each)

Output

180.0 1380.0 345.0
1100.0 366.6666666666667
500.0

Try “Form, Section and disabled()” with live code →

@FocusState and the keyboard

@FocusState tracks which text field has keyboard focus. You read it to know where the user is typing, and write it to move focus or hide the keyboard.

One field: a Bool

struct SearchBox: View {
    @State private var query = ""
    @FocusState private var isFocused: Bool

    var body: some View {
        HStack {
            TextField("Search", text: $query)
                .focused($isFocused)
            if isFocused {
                Button("Cancel") { isFocused = false }   // hides the keyboard
            }
        }
        .onAppear { isFocused = true }                    // show the keyboard
    }
}

Several fields: an optional enum

focused(_:equals:) ties each field to one enum case.
struct LoginView: View {
    enum Field: Hashable { case email, password }

    @State private var email = ""
    @State private var password = ""
    @FocusState private var focus: Field?          // nil means no field focused

    var body: some View {
        Form {
            TextField("Email", text: $email)
                .focused($focus, equals: .email)
                .submitLabel(.next)
            SecureField("Password", text: $password)
                .focused($focus, equals: .password)
                .submitLabel(.go)
        }
        .onSubmit {
            if focus == .email { focus = .password }   // Return moves on
            else { focus = nil; logIn() }             // last field: hide keyboard
        }
        .scrollDismissesKeyboard(.interactively)        // iOS 16+: drag to dismiss
        .toolbar {
            ToolbarItemGroup(placement: .keyboard) {
                Spacer()
                Button("Done") { focus = nil }
            }
        }
    }

    private func logIn() { }
}

The "next field" logic is plain Swift over the enum's cases:

enum Field: CaseIterable {
    case name, email, password
}

func next(after field: Field) -> Field? {
    let all = Field.allCases
    guard let i = all.firstIndex(of: field), i + 1 < all.count else { return nil }
    return all[i + 1]
}

for field in Field.allCases {
    if let following = next(after: field) {
        print("\(field) -> \(following)")
    } else {
        print("\(field) -> hide keyboard")
    }
}

Output

name -> email
email -> password
password -> hide keyboard
Way to dismiss the keyboardHow
Clear focusisFocused = false or focus = nil
Keyboard toolbar button.toolbar { ToolbarItemGroup(placement: .keyboard) { ... } }
Scroll to dismiss (iOS 16+).scrollDismissesKeyboard(.interactively) or .immediately
Return on the last field.onSubmit { focus = nil }

Try “@FocusState and the keyboard” with live code →

onSubmit: add, clear and move focus

A common lab pattern: type something, press Return, and it is added to a list. Three details make it feel right: ignore blank input, clear the field after adding, and keep or move focus so the user can type the next one.

.onSubmit on each field decides what Return does there.
struct QuickNotes: View {
    enum Field: Hashable { case title, detail }

    @State private var title = ""
    @State private var detail = ""
    @State private var notes: [String] = []
    @FocusState private var focus: Field?

    var body: some View {
        VStack(spacing: 12) {
            TextField("Title", text: $title)
                .focused($focus, equals: .title)
                .submitLabel(.next)
                .onSubmit { focus = .detail }          // Return on the title: go to the detail field

            TextField("Detail (optional)", text: $detail)
                .focused($focus, equals: .detail)
                .submitLabel(.done)
                .onSubmit { addNote() }                // Return on the last field: add

            List(notes, id: \.self) { Text($0) }
        }
        .textFieldStyle(.roundedBorder)
        .padding()
        .onAppear { focus = .title }
    }

    private func addNote() {
        let clean = title.trimmingCharacters(in: .whitespacesAndNewlines)
        guard !clean.isEmpty else {                    // blank or only spaces: ignore it
            focus = .title                             // and send the user back to the title
            return
        }
        notes.append(detail.isEmpty ? clean : "\(clean): \(detail)")
        title = ""                                     // clear both fields
        detail = ""
        focus = .title                                 // ready for the next note
    }
}

The decision in addNote is plain Swift, so you can test it without a screen:

func isBlank(_ text: String) -> Bool {
    text.allSatisfy { $0 == " " || $0 == "\n" || $0 == "\t" }
}

var notes: [String] = []
var field = ""

for typed in ["Buy chalk", "   ", "", "Return books"] {
    field = typed
    if isBlank(field) {
        print("ignored")
        continue
    }
    notes.append(field)
    field = ""
}
print(notes)
print(field.isEmpty)

Output

ignored
ignored
["Buy chalk", "Return books"]
true
Goal: Return on Item moves to Amount, the Picker shows the chosen category, and Add stores a non-blank item then clears the field.
import SwiftUI

struct ExpenseEntry: View {
    enum Field: Hashable { case item, amount }
    let categories = ["Food", "Travel", "Books"]

    @State private var item = ""
    @State private var amount = 0.0
    @State private var categoryIndex = 0                    // [A]
    @State private var expenses: [String] = []
    @FocusState private var focus: Field                     // [B]

    var body: some View {
        Form {
            TextField("Item", text: item)                    // [C]
                .focused($focus, equals: .item)
                .onSubmit { focus = .amount }
            TextField("Amount", value: $amount, format: .number)
                .focused($focus, equals: .amount)
            Picker("Category", selection: $categoryIndex) {
                ForEach(categories, id: \.self) { Text($0) }
            }
            Button("Add") {
                expenses.append(item)                        // [D]
            }
            Text("Last amount: \(amount, specifier: "%.2f")")
            ForEach(expenses, id: \.self) { Text($0) }
        }
    }
}
Show the bugs
  • [A] The Picker's options get implicit String tags from ForEach(categories, id: \.self), but the selection is an Int. It compiles, but nothing is ever selected. Fix: @State private var category = "Food" and selection: $category (or loop over categories.indices).
  • [B] With several fields, @FocusState needs an optional enum. A non-optional Field has no default value, so this doesn't compile. Fix: @FocusState private var focus: Field? (nil means no field is focused).
  • [C] text: item passes a String, but TextField needs a Binding<String>: compile error. Fix: TextField("Item", text: $item).
  • [D] Blank items are added, and the field isn't cleared, so a second tap adds a duplicate. Fix: Trim and guard against blank input, append, then set item = "" and focus = .item.

Try “onSubmit: add, clear and move focus” with live code →

@AppStorage and @SceneStorage

@State is lost when the app quits. @AppStorage reads and writes a value in UserDefaults under a key, and redraws the view when it changes. Use it for small preferences.

The default value is used only while UserDefaults has nothing stored for the key.
struct PreferencesView: View {
    @AppStorage("username") private var username = "Guest"
    @AppStorage("darkMode") private var darkMode = false
    @AppStorage("fontSize") private var fontSize = 16.0

    var body: some View {
        Form {
            TextField("Name", text: $username)
            Toggle("Dark mode", isOn: $darkMode)
            Stepper("Font size: \(Int(fontSize))", value: $fontSize, in: 12...30)
        }
    }
}

@SceneStorage("key") saves a value per scene (window) for state restoration: the selected tab, a draft message. The system restores it when it recreates that scene. It is not shared between windows and can be discarded at any time, so don't use it for real data.

@State@Binding@AppStorage@SceneStorage
Owns the value?YesNoYes (in UserDefaults)Yes (per scene)
Survives app relaunch?NoDepends on the ownerYesRestored with the scene, best effort
ScopeOne viewParent's dataWhole appOne window
TypesAnyAnySimple types and raw-value enumsSimple types and raw-value enums
Typical useScreen state: text, togglesChild editing parent's stateUser preferencesSelected tab, unsent draft

Try “@AppStorage and @SceneStorage” with live code →

Exam traps

Code or claimWhat really happens
Changing a plain var inside a view's Button actionCompile error: self is immutable in a view; use @State
@State var count = 0 without privateCompiles, but @State should be private: the view owns it
Setting a @State from the parent through initOnly the first value is used; later parent values are ignored
count vs $countInt value vs Binding<Int>
Passing count to a @Binding var count: Int parameterCompile error: needs $count
@Binding var x = 5Wrong: a binding has no initial value; the parent passes it
Binding in #Preview.constant(value); writes are ignored
Slider(value: $intValue)Compile error: Slider needs a floating-point value
Stepper(..., in: 1...10) at 10, tap +Stays at 10: the range clamps it
Picker tag type differs from selection typeCompiles, but nothing is selected
.keyboardType(.numberPad)Only changes the keyboard; it does not validate input
TextField title vs prompt:Title is the label; prompt: is the placeholder
@FocusState var focus: Field (not optional)Wrong for several fields: use Field?, where nil means no focus
Hide the keyboardSet the @FocusState to false or nil
.disabled(true) on a SectionDisables every control inside it
@AppStorage("key") var items: [String]Compile error: arrays aren't supported directly
Password in @AppStorageInsecure: UserDefaults is plain storage; use the Keychain
Default value in @AppStorage("k") var x = 5Used only until a value is stored under the key
@SceneStoragePer window, for state restoration; not shared, not guaranteed
.scrollDismissesKeyboardiOS 16+
ForEach(names, id: \.self) in a Picker with an Int selectionImplicit tags are String: nothing is selected
Binding(get: { false }, set: ...)The control snaps back: get must read the real state
One @State var isExpanded for every DisclosureGroupAll rows open and close together
Text("\(x, specifier: "%.1f")") vs Text(x, format: .number.precision(.fractionLength(1)))Same output; the format style is type-checked and locale-aware
guard !text.isEmpty for " "Passes: trim whitespace first

Viva questions and answers

Why does SwiftUI need @State at all?

Views are structs that SwiftUI recreates often, and body can't mutate them. @State stores the value outside the struct, keeps it across redraws, and tells SwiftUI to recompute body when it changes.

What is a source of truth?

The single place where a piece of data is stored. Other views read or edit it through bindings rather than keeping their own copies, so the data can never disagree with itself.

@State vs @Binding?

@State owns the data and is the source of truth; it is private and has an initial value. @Binding doesn't own anything; it is a read-write reference to state owned by another view, passed in with $.

What is a projected value?

The extra value a property wrapper exposes through $. For @State and @Binding it is a Binding, which is why you pass $name to a TextField.

Why should @State be private?

It belongs to the view that declares it. A parent setting it through the initializer only affects the first value, which leads to confusing bugs. If the parent should control it, use @Binding.

What is .constant() used for?

It creates a binding with a fixed value that ignores writes. It's mainly used in previews and tests for views that take a @Binding.

Why use value types with @State?

Changing any property of a struct replaces the whole value, which SwiftUI detects as a change. Value types are also copied, so no other code can change them behind the view's back.

What's the difference between a Button's role and its style?

The role (.destructive, .cancel) describes what the button means, and the system uses it for colour and placement. The style (.borderedProminent, .plain) only controls how it looks.

How does a Picker know which option is selected?

Each option has a .tag(value). The Picker compares the tags with its selection binding; the types must match exactly, or nothing is selected.

Does keyboardType validate input?

No. It only chooses the on-screen keyboard. Users can paste text or use a hardware keyboard, so you still validate the value in code.

How do you move focus between text fields?

Declare @FocusState var focus: Field? with a Hashable enum, attach .focused($focus, equals: .email) to each field, and set focus in .onSubmit. Setting it to nil hides the keyboard.

How would you disable a Submit button until a form is valid?

Compute validity from the state in a computed property, for example from a plain validation function returning a list of errors, and apply .disabled(!isValid). It updates automatically as the user types.

What is @AppStorage and what can it store?

A property wrapper that reads and writes UserDefaults under a key and redraws the view on change. It stores Bool, Int, Double, String, URL, Data and Int- or String-raw-value enums.

@AppStorage vs @SceneStorage?

@AppStorage is app-wide and persistent, for preferences. @SceneStorage is per scene, for restoring UI state like a selected tab or a draft, and the system may discard it.

Would you store a login token in @AppStorage?

No. UserDefaults is not encrypted. Secrets belong in the Keychain.

When do you write Binding(get:set:)?

When a control needs a binding to a value you don't store directly, such as "is this row the selected one" derived from one optional id. get computes what to show; set updates the real state.

Why do all DisclosureGroups open together?

They are all bound to the same Bool. Store which row is open (an optional id or a Set) and give each row its own binding.

How does a Picker get tags without .tag()?

From ForEach: each option's id becomes its tag. With id: \.self over strings the tags are strings, so the selection must be a String.

specifier vs format style?

specifier: "%.1f" is a printf string inside Text interpolation. format: .number.precision(.fractionLength(1)) is a type-checked FormatStyle that also handles currency, percent and locale, and works with TextField too.

How do you make Return add an item properly?

In .onSubmit, trim the text, ignore it if blank, append it, clear the field and set the @FocusState back to that field.

Quiz

  1. Why can't a Button action in a view change a plain stored property var count = 0?

    Show the answer

    self is immutable inside a view struct's body

    A view is a struct and body isn't mutating. @State keeps the value outside the struct.

  2. What is the projected value $name of @State private var name = ""?

    Show the answer

    A Binding<String>

  3. Which property wrapper should a child view use to edit a value its parent owns?

    Show the answer

    @Binding

  4. How do you preview a view with @Binding var isOn: Bool?

    Show the answer

    MyView(isOn: .constant(true))

    .constant(true) creates a Binding<Bool> that ignores writes.

  5. Which declaration does Apple recommend for view-owned state?

    Show the answer

    @State private var score = 0

  6. A parent creates ChildView(start: 5) and ChildView copies start into @State private var value. The parent later passes 9. What does the child show?

    Show the answer

    5

    @State uses its initial value only the first time; afterwards it keeps its own stored value.

  7. Which does NOT compile?

    Show the answer

    Slider(value: $level, in: 0...5)

    Slider needs a floating-point binding such as Binding<Double>.

  8. A Picker's selection is a String, but each option has .tag(index) with an Int. What happens?

    Show the answer

    Nothing is ever selected

  9. Which Picker style shows a row of segments?

    Show the answer

    .segmented

  10. What does prompt: set on a TextField?

    Show the answer

    The placeholder text

  11. Which modifier stops iOS capitalising the first letter of an email field?

    Show the answer

    .textInputAutocapitalization(.never)

  12. How do you allow only past dates in a DatePicker?

    Show the answer

    in: ...Date.now

  13. What does .disabled(username.isEmpty) do?

    Show the answer

    Greys out the control and ignores taps while the name is empty

  14. For several text fields, what type should @FocusState have?

    Show the answer

    An optional Hashable enum, like Field?

    nil means no field is focused; each field uses .focused($focus, equals: .case).

  15. How do you hide the keyboard with @FocusState private var isFocused: Bool?

    Show the answer

    isFocused = false

  16. Where does @AppStorage keep its value?

    Show the answer

    In UserDefaults under the given key

  17. Which type can @AppStorage store directly?

    Show the answer

    An enum with a String raw value

  18. What is @SceneStorage for?

    Show the answer

    Restoring small per-window state like the selected tab

  19. Ten toggles must allow only one item on at a time. What is the cleanest state?

    Show the answer

    One @State var selected: ID? and a Binding(get:set:) per toggle

  20. @State private var pick = 0 and Picker("P", selection: $pick) { ForEach(["a", "b"], id: \.self) { Text($0) } }. What happens?

    Show the answer

    Nothing is selected: the implicit tags are Strings

  21. Which shows 4.4 for let r = 4.36?

    Show the answer

    Text(r, format: .number.precision(.fractionLength(1)))

  22. A TextField outside a Form shows no border. What adds one?

    Show the answer

    .textFieldStyle(.roundedBorder)

  23. In an onSubmit that adds an item, what should happen when the text is only spaces?

    Show the answer

    Ignore it (after trimming) and keep focus in the field

← SwiftUI fundamentals · Lists, observation and environment →

Practise this lesson interactively →