skip to content

A SwiftUI sleep-timer Picker bound to a Double shows no selection and ignores taps, though every row has a tag; why, and how do you fix it?

level: seniorimportance: should knowfreq 42%

answer

  1. tags are typed values
  2. an integer literal infers Int
  3. Picker looks up tags of its selection type
  4. implicit ForEach tags use id
  5. Optional tags come for free

basics

~20 s

Each .tag(15) infers an Int tag, but the Picker looks for tags of its selection type, Double, so no row matches. Tag with the same type, such as .tag(15.0), or model the choices as an enum.

solid answer

~40 s

`tag(_:)` is generic over any `Hashable`, so `.tag(15)` compiles and stores an `Int`. A `Picker` bound to `$sleepMinutes: Double` looks for tags of type `Double`; finding none, it shows no row as selected and has no value to write back when a row is tapped. Nothing warns at compile time. Fix it by making the types agree — `.tag(15.0)` or `.tag(Double(15))` — or better, replace the number with an enum that carries its minutes. The same failure appears when `ForEach` supplies tags from an `id` whose type differs from the selection, such as a `UUID` while the selection is the model. Optional selections are not the problem with a current SDK: `tag(_:includeOptional:)` defaults to also writing the `Optional` tag.

code

swift · 25 lines
swift
import SwiftUI

struct SleepTimerPicker: View {
    @State private var sleepMinutes: Double = 15

    var body: some View {
        Picker("Sleep timer", selection: $sleepMinutes) {
            Text("Off").tag(0)
            Text("15 minutes").tag(15)
            Text("30 minutes").tag(30)
        }
    }
}

struct SleepTimerPickerFixed: View {
    @State private var sleepMinutes: Double = 15

    var body: some View {
        Picker("Sleep timer", selection: $sleepMinutes) {
            Text("Off").tag(0.0)
            Text("15 minutes").tag(15.0)
            Text("30 minutes").tag(30.0)
        }
    }
}

go deeper

for a junior

Recall that a Picker selects rows by tag and that the tag must be the same type as the selection.

for a middle

Explain how literal type inference and ForEach's id-based tags produce tags of the wrong type without any compile error.

for a senior

Diagnose the silent mismatch from the symptoms, fix it with typed tags or an enum, and check that the initial value is one of the options.

for a principal

Encourage enum-backed pickers as a review rule, so the type system rather than runtime testing keeps tags and selections aligned.

## The symptom A podcast app offers a sleep timer: Off, 15 minutes, 30 minutes. The state is `@State private var sleepMinutes: Double = 15`, and each row has a tag. Yet the picker shows no current value, and tapping a row changes nothing. The code compiles cleanly, which is what makes this a senior debugging question. ```swift Picker("Sleep timer", selection: $sleepMinutes) { Text("Off").tag(0) Text("15 minutes").tag(15) Text("30 minutes").tag(30) } ``` ## Why it happens: tags are typed `tag(_:)` is declared as `func tag<V>(_ tag: V, includeOptional: Bool = true) -> some View where V : Hashable`. The tag is a value **of a specific type**, chosen by type inference at the call site. An integer literal with no other context becomes an **`Int`**, so the rows carry `Int` tags `0`, `15` and `30`. A `Picker` is generic over its `SelectionValue`, here `Double`. Apple's documentation says to tag each view so that *the type of each selection matches the type of the bound state variable*. The picker therefore: 1. looks among its rows for a tag of type `Double` equal to `15.0` — there is none, so no row is shown as selected; 2. when a row is tapped, looks for that row's `Double` tag to write back — there is none, so the binding is never written. Nothing in the type system connects the tag's type to the picker's selection type, so the compiler cannot catch the mismatch. ## Fixes, from quickest to best - **Match the literal's type:** `.tag(15.0)`, or `.tag(Double(15))`. Every row must be fixed — one stray `Int` row is simply unselectable. - **Match the state's type to the tags:** if the minutes are always whole, make the state an `Int`. Persisted values and the code that reads them must change too. - **Model the choice as an enum:** `enum SleepTimer: Int, CaseIterable, Identifiable { case off = 0, quarterHour = 15, halfHour = 30; var id: Self { self } }`. Bind the picker to a `SleepTimer`, loop with `ForEach(SleepTimer.allCases)`, and convert to a duration where the timer is started. The tags and the selection now cannot disagree, and the compiler checks every `switch` over the cases. ## The same bug in other clothes | Selection type | Tags actually written | Result | |---|---|---| | `Double` | `.tag(15)` → `Int` | no match | | `Show` (a model) | `ForEach(shows)` → each show's `id`, a `UUID` | no match | | `Flavor` (an enum) | `ForEach` with `var id: String { rawValue }` → `String` | no match; Apple's documentation names this case | | `Flavor?` | `.tag(Flavor.vanilla)` | **matches** — see below | When `ForEach` builds the rows, it tags each one with its element's **`id`**, so the `id` type must equal the selection type, or you add an explicit `.tag(_:)` that overrides it. ## Optional selections are handled A `Picker` bound to `Flavor?` — an "unset" state — looks as if it should hit the same problem, since the tags are `Flavor` and the selection is `Flavor?`. With a current SDK it does not: `tag(_:includeOptional:)` writes the tag for both `V` and `Optional<V>` unless you pass `includeOptional: false`, and the documentation says a `ForEach` row can omit the explicit tag when the element's `id` and the selection have the same type or the same type made optional. The iOS 27 SDK's interface shows the modifier's body exported into the calling app, with a branch that writes both tags on releases before iOS 26, so the behaviour comes from the SDK you build with rather than from the device's iOS version. ## Diagnosing it quickly - Print `type(of:)` of the state and compare it with the literal or `id` type you tag with. - Check that the **initial value** is one of the tag values: a `sleepMinutes` of `20` matches no row even with correct types. - Temporarily add `Text("\(sleepMinutes)")` beside the picker to see whether taps write the binding at all. - In code review, treat untyped numeric literals in `.tag(_:)` as suspect whenever the selection is not `Int`. The rule a senior engineer states: **a picker matches by type and value, and only the type of the tag is invisible at the call site.**

  • Why does the compiler accept .tag(15) for a Picker whose selection is a Double?
    `tag(_:)` is a generic modifier on every view, accepting any `Hashable` value, and it knows nothing about the `Picker` that will later read it. The literal `15` has no contextual type, so it defaults to `Int`. The mismatch only shows at runtime, when the picker finds no tag of its own selection type.
  • How do you add a None row to a Picker bound to an optional Flavor? selection?
    Tag the row with a nil of the selection's own type: `Text("None").tag(Flavor?.none)`. The tag's type is then `Optional<Flavor>`, the picker's selection type, and its value matches a `nil` selection. A bare `.tag(nil)` gives the compiler no type to infer, so spell the optional type out.
  • The types match, yet the picker shows no selection on first appearance; what else do you check?
    That the initial state equals one of the tag values. A selection of `20.0` when the rows are tagged `0.0`, `15.0` and `30.0` matches no row, so nothing is shown as selected until the user picks one. Initialise the state from a valid option or model the options as an enum.

A cloakroom matches tickets by colour and number: a blue ticket 15 never retrieves the coat filed under a red 15, however equal the numbers look.

  • A Picker matches rows by their displayed Text
  • An integer literal tag adapts to a Double selection
  • An optional selection always needs Optional tags written by hand
  • The compiler would reject a tag of the wrong type
  • ForEach rows never need explicit tags

Assumes the iOS 27 SDK, whose tag(_:includeOptional:) also writes the Optional tag by default and is compiled into the app.