skip to content

In SwiftUI, how do you bind a Toggle and a Picker over an enum to a settings screen's state?

level: juniorimportance: must knowfreq 75%

answer

  1. two-way bindings, not values
  2. Toggle wants a Binding<Bool>
  3. tag type equals selection type
  4. ForEach tags each row with its id

basics

~20 s

Bind a Toggle to a Bool with Toggle("Title", isOn: $flag) and a Picker to an enum with Picker("Title", selection: $choice); give every row a tag of that enum type, which ForEach over an Identifiable enum does for you.

solid answer

~50 s

Both controls take a two-way binding to state the screen owns. `Toggle("Download on Wi-Fi only", isOn: $wifiOnly)` reads and writes a `Bool`. A `Picker` takes `selection:` bound to any `Hashable` value, usually an enum that is `CaseIterable` and `Identifiable` with `var id: Self { self }`. Each row is matched to a selection value through its tag: write `.tag(SkipInterval.fifteen)` by hand, or build the rows with `ForEach(SkipInterval.allCases)`, which tags each row with the element's `id` — so the `id` type must be the selection type. The picker then shows the matching row as selected and writes the tapped row's tag back. How both controls look depends on context: inside a `Form` on iOS a toggle is a switch row and a picker is a row showing its current value, and `toggleStyle(_:)` or `pickerStyle(_:)` override that.

code

swift · 22 lines
swift
import SwiftUI

enum SkipInterval: Int, CaseIterable, Identifiable {
    case ten = 10, fifteen = 15, thirty = 30
    var id: Self { self }
}

struct PlaybackSettings: View {
    @State private var downloadOnWiFiOnly = true
    @State private var skipInterval: SkipInterval = .fifteen

    var body: some View {
        Form {
            Toggle("Download on Wi-Fi only", isOn: $downloadOnWiFiOnly)
            Picker("Skip forward", selection: $skipInterval) {
                ForEach(SkipInterval.allCases) { interval in
                    Text("\(interval.rawValue) seconds")
                }
            }
        }
    }
}

go deeper

for a junior

Recall that Toggle binds to a Bool with isOn and Picker binds to a Hashable selection, and that rows are matched by tag, not by their text.

for a middle

Explain how ForEach supplies tags from each element's id and why the id type must equal the selection type for an enum picker.

for a senior

Show that you model settings as enums with stable cases, keep one source of truth, and know which container changes a control's style.

for a principal

Frame the choice of enum-backed settings as a team convention that keeps persisted values, pickers and the code that reads them consistent.

## What the two controls need A settings screen in SwiftUI is mostly controls bound to state. **`Toggle`** and **`Picker`** are the two you write first, and both follow the same rule: the control does not own the value, it holds a **`Binding`** to a value the screen owns, usually in `@State` or in an observable model. - `Toggle` takes `isOn:` — a `Binding<Bool>`. Pass `$downloadOnWiFiOnly`, the projected value of a `@State var downloadOnWiFiOnly = true`. - `Picker` takes `selection:` — a `Binding<SelectionValue>`, where `SelectionValue` is any `Hashable` type. - Both have a convenience initialiser whose first argument is a title string, which SwiftUI turns into a `Text` label. Passing a plain `Bool` instead of a binding does not compile. Passing `.constant(true)` compiles but the switch can never change, because a constant binding ignores writes. ## How a Picker knows which row is which A `Picker` matches rows to values through **tags**. Each row view carries a tag set with `tag(_:)`, and the picker: 1. reads the current `selection` and shows the row whose tag equals it as selected; 2. when the user picks a row, writes that row's tag into the binding. Apple's documentation states the rule plainly: the type of each tag must match the type of the bound state variable. For an enum that is simple, because each tag is a case: ```swift Picker("Skip forward", selection: $skipInterval) { Text("10 seconds").tag(SkipInterval.ten) Text("15 seconds").tag(SkipInterval.fifteen) } ``` ## Letting ForEach write the tags Listing every case by hand does not scale, so the usual pattern makes the enum **`CaseIterable`** and **`Identifiable`** and loops with `ForEach(SkipInterval.allCases)`. A `ForEach` automatically tags each row with its element's **`id`**. That only helps when the `id` type is exactly the selection type, which is why the idiom is: ```swift enum SkipInterval: Int, CaseIterable, Identifiable { case ten = 10, fifteen = 15, thirty = 30 var id: Self { self } } ``` If the enum instead declared `var id: Int { rawValue }`, the automatic tags would be `Int` values while the selection is a `SkipInterval`, and no row would match. Apple's Picker documentation calls out this exact case and says to add an explicit `.tag(_:)` when the `id` type differs from the selection type. ## How the controls look depends on where they sit Neither control has one fixed appearance. SwiftUI picks a style from the platform and the container: | Control | Inside a `Form` on iOS | Override with | |---|---|---| | `Toggle` | a row with the label and a switch | `toggleStyle(.switch)` or `toggleStyle(.button)` | | `Picker` | a row with the label and the current value; tapping it offers the choices | `pickerStyle(.segmented)`, `.menu`, `.inline`, `.wheel`, `.navigationLink` | Both style modifiers apply to every matching control in the subtree they wrap, so one `.toggleStyle(.switch)` on a `VStack` styles all the toggles inside it. ## Habits that keep a settings screen honest - **Own the value in one place.** The `@State` (or the observable settings model) is the source of truth; the controls only edit it through bindings. - **Model choices as an enum,** not as strings or magic numbers. The compiler then keeps the tags, the stored value and the switch statements that consume it in step. - **Keep the `id` equal to the case** when the enum feeds a picker, or tag explicitly. - **Give every control a real title,** even when a style hides it visually: the title also names the control for VoiceOver. ## Mistakes that show up in review - **A `Toggle` aimed at a read-only computed property.** It has no `$` projection to pass; bind a stored property, or build a `Binding(get:set:)` deliberately. - **Tags on the wrong view.** `.tag(_:)` belongs on each row view inside the picker's content, not on the `Picker` itself. - **An initial selection that matches no row.** If the state starts at a value no tag equals, the picker shows nothing selected until the user chooses. - **Rebuilding the option list from strings.** Renaming a label then silently changes the stored value; an enum case keeps its identity when its display text changes. ## Where this sits This is the junior baseline for every settings screen in SwiftUI. What goes wrong when a tag's type quietly differs from the selection's, how a `Form` restyles each control, and how a screen validates its input before it saves are separate, deeper questions.

  • Why does the enum declare var id: Self { self } rather than using its raw value as the id?
    A `ForEach` tags each row with its element's `id`. The picker's selection is the enum, so the tags must be enum values too. With `var id: Int { rawValue }` the automatic tags would be `Int`s that never equal a `SkipInterval`, and no row would be selected or selectable until you add explicit `.tag(_:)` calls.
  • How do you show a Toggle as a tappable button instead of a switch?
    Apply `toggleStyle(.button)` to the toggle or to a container around it. The button style draws the toggle as a button whose appearance shows the on state. It is available from iOS 15; `toggleStyle(.switch)` forces the switch look, and the automatic style lets SwiftUI choose by platform and context.

  • Passing a plain Bool to Toggle's isOn instead of a binding
  • Expecting a Picker to match rows by their visible text
  • Using the raw value as the id and leaving the rows untagged
  • Storing the picker choice as a free-form String instead of an enum
  • Believing a Toggle looks the same in every container