skip to content

In SwiftUI, how do you show a transaction's amount and date with Text(_:format:) instead of a hand-built string, and what does it handle for you?

level: middleimportance: must knowfreq 65%

answer

  1. a value plus a FormatStyle
  2. currency(code:) on a Decimal
  3. the environment's locale
  4. formatted once per body vs live

basics

~20 s

Text(amount, format: .currency(code: "EUR")) and Text(date, format: .dateTime.day().month()) format the value for the environment's locale when body runs. A relative date formatted this way does not tick; iOS 18 adds Text(.currentDate, format:) styles that update live.

solid answer

~40 s

`Text(_:format:)` (iOS 15) takes the value and a Foundation `FormatStyle`, so the view keeps the number or date and SwiftUI produces the string: `Text(amount, format: .currency(code: code))` gets grouping, decimal separator and symbol placement right, and `Text(date, format: .dateTime.day().month(.abbreviated))` orders the fields for the locale. Text formats with the locale in the SwiftUI environment. The string is produced when `body` runs, so a relative date such as `.relative(presentation: .named)` stays "2 minutes ago" until something re-renders the row; on iOS 18 `Text(.currentDate, format: .reference(to: date))` updates as the clock advances. Inside a literal, `Text("Paid \(amount, format: .currency(code: code))")` formats the value and keeps one localization key.

code

swift · 34 lines
swift
import SwiftUI

struct Transaction {
    let merchant: String
    let amount: Decimal
    let currencyCode: String
    let date: Date
}

struct AmountAndDate: View {
    let transaction: Transaction

    var body: some View {
        HStack(alignment: .firstTextBaseline) {
            VStack(alignment: .leading) {
                Text(transaction.merchant)
                Text(transaction.date, format: .dateTime.day().month(.abbreviated))
                    .foregroundStyle(.secondary)
            }
            Spacer()
            Text(transaction.amount, format: .currency(code: transaction.currencyCode))
                .monospacedDigit()
        }
    }
}

@available(iOS 18.0, *)
struct LiveAge: View {
    let date: Date

    var body: some View {
        Text(.currentDate, format: .reference(to: date))   // keeps updating
    }
}

go deeper

for a junior

Recall Text(_:format:) with .currency(code:) for amounts and .dateTime fields for dates, and that the view keeps the value rather than a string.

for a middle

Explain that the string is produced from the environment's locale when body runs, why money is a Decimal with the transaction's own code, and how interpolating a format style keeps one localization key.

for a senior

Diagnose a relative date that goes stale on screen and choose between the iOS 18 live styles and a TimelineView for older releases; catch formatters allocated in body.

for a principal

Decide where formatting lives for a team: values in models, format styles at the view, and a rule against hand-assembled amount strings that only work in the developers' locale.

## The problem with hand-built strings A transaction row needs an amount like `€1,234.50`, a date like `21 Sept` and maybe "yesterday". Building these with string interpolation of a `Double`, or with a `NumberFormatter` created in `body`, gets the grouping separator, the decimal mark, the symbol position and the field order wrong for most of the world, and allocates a formatter on every render. SwiftUI's answer is to pass **the value and a format style** to `Text`: - `Text(_:format:)` (iOS 15) takes any `Equatable` input and a `FormatStyle` whose output is a `String`. - An iOS 18 overload accepts a format style that outputs an `AttributedString`. - The older `Text(_:formatter:)` still takes a Foundation `Formatter` object. ## Amounts `Text(amount, format: .currency(code: "EUR"))` formats a `Decimal`, `Double` or integer as money. Practical points: 1. **Store money as `Decimal`**, not `Double`; the currency style formats either, but only `Decimal` keeps cents exact before they reach the view. 2. **The currency code comes from the transaction**, not the device: a euro charge stays in euros for a user whose phone is set to the US. 3. **Text formats with the environment's `\.locale`**, so the same euro amount reads `€1,234.50` in one locale and `1.234,50 €` in another. Setting the locale is the localization lesson's subject; the point here is that you never place separators yourself. 4. **Add `monospacedDigit()`** to a column of amounts so digits align as values change. ## Dates `Date.FormatStyle` builds a date from the fields you ask for, and the locale decides their order and spelling: | Format | Example output (varies with the locale) | |---|---| | `.dateTime.day().month(.abbreviated)` | `21 Sept` or `Sep 21` | | `.dateTime.hour().minute()` | `14:05` or `2:05 PM` | | `.relative(presentation: .named)` | `yesterday`, `in 2 hours` | | `Text(.currentDate, format: .reference(to: date))` (iOS 18) | `in 5 minutes`, updating | ## Formatted once, or live `Text(date, format: .relative(presentation: .named))` computes its string **when `body` evaluates**. It says "2 minutes ago" until something else re-renders the row, so a list left on screen grows stale. Two fixes: - On iOS 18 and later, SwiftUI's `SystemFormatStyle` styles (`.reference(to:)`, `.offset(to:)`, `.timer(countingDownIn:)`, `.stopwatch(startingAt:)`) used with `Text(.currentDate, format:)`, whose first argument is a `TimeDataSource`; Apple's documentation says they update as the system clock advances, with SwiftUI scheduling the updates. - On iOS 17, keep the value-based relative style and drive refreshes yourself, for example with a `TimelineView` around the row. ## Formatting inside a sentence `LocalizedStringKey`'s interpolation accepts a format style (iOS 15), so `Text("Paid \(amount, format: .currency(code: code)) at \(merchant)")` formats the amount and still produces one key for translators instead of three fragments. Joining separately formatted strings is the mistake this replaces. ## Other values a row formats The same initializer covers most of what a transaction screen shows, each with a Foundation style: - `Text(tags, format: .list(type: .and))` joins `["Groceries", "Shared"]` with the locale's separators and conjunction. - `Text(rate, format: .percent.precision(.fractionLength(1)))` shows an interest rate such as `4.2%`. - `.currency(code:)` accepts `.precision(.fractionLength(0))` for a rounded summary figure. - `Text(amount, format: .number)` shows a plain grouped number. Because the view holds the value, a change to the value or to the environment's locale re-renders the text without any string bookkeeping in the model. Keeping values in the model also means the same `Decimal` can be summed, compared and sorted, which a pre-formatted string cannot. ## Findings that come up in review - `Text("\(amount)")` on a `Double`, which goes through a printf-style specifier and shows six decimal places and no currency symbol, such as `1234.500000`. - `Text(String(format: "%.2f €", value))`, which hard-codes the symbol's position and the decimal mark. - A `DateFormatter` or `NumberFormatter` created inside `body` on every evaluation. - A "last updated 2 minutes ago" label that silently goes stale because nothing re-renders it. - An amount column without `monospacedDigit()`, so digits shift as values change. Each of these has the same fix: hand `Text` the value and a format style, and decide explicitly whether the result needs to stay live. ## What it does not do - It does not choose the currency; the code is your data. - It does not convert between currencies or round to a cash rule. - A value-based relative date does not refresh on its own.

  • Why not create a NumberFormatter inside body and pass its string to Text?
    It works but repeats work SwiftUI already does: a formatter is allocated on every body evaluation, the view holds a string instead of the value, and the formatter's locale is whatever you remembered to set. `Text(_:format:)` keeps the value, uses the environment's locale and lets the format style be a cheap value type.
  • How do you keep "5 minutes ago" current in a transaction list on iOS 17?
    The iOS 18 `SystemFormatStyle` styles are not available, so a value-based `.relative(presentation:)` string must be re-rendered. Wrap the rows that show it in a `TimelineView(.everyMinute)` and format from the timeline's date, or refresh a model value on a timer; both re-run body so the string is recomputed.

  • Text(date, format: .relative(presentation: .named)) keeps updating on its own
  • The currency code should come from the device's region
  • String interpolation of a Double is fine for showing money
  • Format styles need a NumberFormatter created alongside them
  • Formatting amounts separately and concatenating strings localizes correctly

Assumes the iOS 27 SDK; Text(_:format:) is iOS 15, and the live Text(.currentDate, format:) styles in SystemFormatStyle need iOS 18.