skip to content

A SwiftUI checkout form binds its postcode TextField to an Int with format: .number; why does it lag behind typing and drop leading zeros, and what do you use instead?

level: seniorimportance: should knowfreq 42%

answer

  1. value bindings wait for a commit
  2. an identifier, not a quantity
  3. locale grouping on format
  4. lenient parse strategy
  5. String plus filter in onChange

basics

~10 s

A value-bound TextField writes the Int only when the edit is committed, and an Int cannot keep leading zeros or letters. Bind a String, use keyboardType(.numberPad) and textContentType(.postalCode), and filter to digits in onChange(of:).

solid answer

~40 s

`TextField(_:value:format:)` converts text to the bound type through a format style, and Apple's documentation says a non-string binding is updated only when the user commits, such as by pressing Return, while a `String` updates per keystroke. A number pad on iPhone has no Return key, so the derived UI lags. An `Int` is also the wrong model: `02134` parses to `2134`, the `.number` style shows it with grouping as `2,134`, and Foundation's lenient parse turns `12a` into `12`. Bind a `String` instead, add `.keyboardType(.numberPad)` and `.textContentType(.postalCode)`, and in `onChange(of:)` strip anything outside `0`-`9` and cap the length, because the keyboard type does not stop pasted or hardware-keyboard input. Then validate before payment.

code

swift · 13 lines
swift
import SwiftUI

struct PostcodeAsInt: View {
    @State private var postcode = 0

    var body: some View {
        Form {
            TextField("Postcode", value: $postcode, format: .number)
                .keyboardType(.numberPad)
            Text("Saved postcode: \(postcode)")
        }
    }
}

go deeper

for a junior

Remember that a String binding updates as you type, while a TextField bound to a number with format: updates only when the edit is committed.

for a middle

Explain how the format style converts text both ways, why grouping separators appear, and why a number pad does not filter input.

for a senior

Diagnose the lag and lost zeros from commit semantics and the wrong model type, then ship the String-plus-filter fix with validation and a keyboard toolbar.

for a principal

Push a modelling rule for forms: identifiers stay strings, quantities use format styles, and every number-pad field gets a way to move on.

## The symptom A checkout form needs a postcode field that only accepts digits. A tempting shortcut binds it to a number: ```swift import SwiftUI struct PostcodeAsInt: View { @State private var postcode = 0 var body: some View { Form { TextField("Postcode", value: $postcode, format: .number) .keyboardType(.numberPad) Text("Saved postcode: \(postcode)") } } } ``` In testing, three things go wrong: the "Saved postcode" line does not follow the typing, a postcode such as `02134` comes back as `2,134`, and a stray letter typed after the digits is silently dropped from the value. Each has a cause in how SwiftUI and Foundation treat a **value-bound** text field. ## Cause 1: the binding updates only on commit `TextField(_:value:format:prompt:)` (iOS 15) binds to a non-string value and uses a **format style** to convert between the value and the text on screen. Apple's documentation says that for non-string types the field **updates the value when the user commits their edits, such as by pressing the Return key**, whereas a `String` binding updates continuously. So while the user types, the `Int` still holds the old number, and anything derived from it (a validation message, an enabled Pay button, the summary line) lags behind. On iPhone the number pad makes this worse: it has **no Return key**, so the user cannot commit that way at all. ## Cause 2: an `Int` is the wrong model for a postcode A postcode is an **identifier made of characters**, not a quantity: - **Leading zeros vanish.** The text `02134` parses to the integer `2134`; there is no integer that remembers the zero. - **Grouping separators appear.** The `.number` style formats with the locale's grouping, so in a US English locale `2134` is shown as `2,134`, and `12345` as `12,345` (`12.345` in a German locale). - **Parsing is lenient.** Foundation's integer parse strategy, which the format style supplies, reads `12a` as `12` and rejects `SW1A`. Postcodes that contain letters cannot be represented at all. None of this is a SwiftUI bug: the field did what the format style asked. ## The fix: a String with a keyboard, a content type and a filter Keep the postcode as a `String`, describe the field to the system, and enforce the rule yourself: ```swift import SwiftUI struct PostcodeRow: View { @Binding var postcode: String var body: some View { TextField("Postcode", text: $postcode) .keyboardType(.numberPad) .textContentType(.postalCode) .onChange(of: postcode) { _, newValue in let digits = String(newValue.filter { "0123456789".contains($0) }.prefix(5)) if digits != newValue { postcode = digits } } } } ``` 1. **`String` binding** — the value updates on every keystroke, keeps leading zeros and never gains separators. 2. **`.keyboardType(.numberPad)`** — shows digits only, but it is a layout, not a filter: paste, dictation and hardware keyboards can still deliver other characters. 3. **`.textContentType(.postalCode)`** — lets the system offer the user's own postcode as a suggestion. 4. **`onChange(of:)`** (the two-parameter form, iOS 17) — strips anything outside `0`-`9` and caps the length; writing the cleaned string back runs the closure once more, finds nothing to change and stops. Matching an explicit `"0123456789"` avoids `Character.isNumber`, which is also true for characters such as `½` and Arabic-Indic digits. 5. **Validation before payment** — the filter keeps characters out; checking the length and region rules still happens when the user taps Pay. Because the number pad has no Return key, the postcode row also needs a **Next** button in a `.keyboard` toolbar that assigns the next `@FocusState` case. ## When a value-bound field is right | Field | Bind to | Why | |---|---|---| | Postcode, card number, phone | `String` | Identifiers: leading zeros and exact characters matter | | Tip amount, quantity | `Decimal` or `Int` with a format style | Real numbers you compute with; commit-on-Return is acceptable | | Name parts | `PersonNameComponents` with `.name(style:)` | Structured value the format style can parse | When you do use a value-bound field, design for commit semantics: compute totals from the committed value, and give number-pad fields a way to commit or move on.

  • Why not rely on .keyboardType(.numberPad) alone to keep letters out?
    The keyboard type only chooses the software keyboard. Text can still arrive by paste, dictation, AutoFill or a hardware keyboard on iPad, and the binding receives it unchanged. The filter in `onChange(of:)` is what enforces digits; the number pad just makes the common path easier.
  • When is TextField(_:value:format:) the right choice in a checkout?
    For real numbers you compute with, such as a tip amount bound to a `Decimal` with a currency format or a quantity bound to an `Int`. You accept that the value changes on commit, compute totals from the committed value, and give number-pad fields a toolbar button so the user can move on.

  • A value-bound TextField updates its Int on every keystroke, like a String binding
  • keyboardType(.numberPad) guarantees the bound string contains only digits
  • Binding a postcode to Int is fine because postcodes are made of digits
  • Character.isNumber is a safe filter for ASCII digits 0 to 9
  • The grouping separator in the field is a SwiftUI rendering bug