---
name: swift-formatstyle
description: "Display formatting with FormatStyle (iOS 15+): integers, floating point, decimals, currency, percentages, dates, date ranges, relative and anchored relative dates, durations (Duration.TimeFormatStyle, Duration.UnitsFormatStyle, iOS 16+), measurements, person names, byte counts, lists, URLs (iOS 16+), parsing, custom FormatStyle conformances. Use when formatting values for display, replacing legacy Formatter subclasses, or writing a custom format style. String Catalogs, plurals and RTL review belong to ios-localization."
metadata:
  source: multi-agent-pipeline
---

# Swift FormatStyle

`FormatStyle` describes how one kind of value becomes text, as a small typed
value you can chain and reuse, instead of configured `Formatter` objects. Foundation caches the
expensive machinery behind them, so a style can be written inline wherever a
value is shown. Availability: iOS 15 for the protocol and most styles, iOS 16
for the `Duration` and `URL` styles, iOS 18 for `Date.AnchoredRelativeFormatStyle`.

## Locale review is part of the job

Formatting output changes with the user's region even in an app that ships one
language. Whenever this skill is used, recommend previewing or testing at least
`en_US`, `de_DE`, `ar_SA` and `ja_JP`, and check:

- decimal and grouping separators,
- the numbering system (Arabic-Indic digits in `ar_SA`),
- calendar and date order,
- where the currency sign goes and which units people expect,
- right-to-left output, and any layout that depends on the string's length.

Work on String Catalogs, bundles, plural rules, translated copy and RTL layout
review belongs to `ios-localization`. "We are not adding languages" is not a
reason to skip that review.

## Quick reference

| Value | Style | Example output (en_US) |
| --- | --- | --- |
| `Int`, `Double` | `.number` | `9.formatted(.number.precision(.fractionLength(2)))` gives "9.00" |
| Currency | `.currency(code:)` | 12.5 with `"USD"` gives "$12.50" |
| Percent | `.percent` | 0.4 gives "40%" |
| `Date` | `.dateTime` | `.dateTime.month().day().year()` gives "Mar 3, 2026" |
| Date range | `.interval` | `(opening..<closing).formatted(.interval)` |
| Relative date | `.relative(presentation:unitsStyle:)` | `.named` gives "yesterday" |
| `Duration` | `.time(pattern:)` | 3661 seconds as `.hourMinuteSecond` is "1:01:01" |
| `Duration` | `.units(allowed:width:)` | 90 seconds is "1 min, 30 sec" |
| `Measurement` | `.measurement(width:)` | "72°F" |
| `PersonNameComponents` | `.name(style:)` | "Ada Lovelace" |
| `[String]` | `.list(type:width:)` | three names with `.and` read "Mina, Omar, and Lea" |
| Byte count | `.byteCount(style:)` | one mebibyte (1,048,576 bytes) with `.memory` is "1 MB" |
| `URL` | `.url` | `.url.scheme(.never).host().path()` drops "https://" and the query |

## Numbers

Plain `formatted()` already follows the user's locale: 2500000 shows as
"2,500,000" in `en_US` and "2.500.000" in `de_DE`.

```swift
let upToTwo = FloatingPointFormatStyle<Double>.number.precision(.fractionLength(0...2))
let threeSignificant = FloatingPointFormatStyle<Double>.number.precision(.significantDigits(3))
(7.0 / 3.0).formatted(upToTwo)            // "2.33"
(7.0 / 3.0).formatted(threeSignificant)   // "2.33"

let seats = 1834
seats.formatted(.number.rounded(rule: .down, increment: 100))   // "1,800"
seats.formatted(.number.grouping(.never))                       // "1834"
seats.formatted(.number.sign(strategy: .always()))              // "+1,834"
seats.formatted(.number.locale(Locale(identifier: "fr_FR")))    // "1 834"

let audience = 3_400_000
audience.formatted(.number.notation(.compactName))              // "3.4M"
0.00042.formatted(.number.notation(.scientific))                // "4.2E-4"
```

The styles behind these are `IntegerFormatStyle` and
`FloatingPointFormatStyle` (and `Decimal.FormatStyle`).

## Currency

The ISO 4217 code decides the symbol and the usual number of fraction digits,
so yen shows no decimals:

```swift
18.75.formatted(.currency(code: "EUR"))   // "€18.75" in en_US
30.0.formatted(.currency(code: "JPY"))    // "¥30"
```

To override precision, build the style explicitly:

```swift
let noCents = FloatingPointFormatStyle<Double>.Currency(code: "USD")
    .precision(.fractionLength(0))
let price = 1299.99
price.formatted(noCents)                  // "$1,300"
```

## Percentages

A floating-point value is a fraction; an integer is already a percentage.

```swift
let completion = 0.8567
completion.formatted(.percent)                                   // "85.67%"
completion.formatted(.percent.precision(.fractionLength(1)))     // "85.7%"
let passRate = 42
passRate.formatted(.percent)                                     // "42%"
```

## Dates

Build exactly the fields you want; the locale decides order and punctuation.

```swift
let launch = Date.now
launch.formatted(.dateTime.day().month().year())            // "Mar 3, 2026" (order comes from the locale)
launch.formatted(.dateTime.minute().hour())                 // "4:05 PM"
let spelledOut = Date.FormatStyle.dateTime.day().month(.wide).weekday(.wide)
launch.formatted(spelledOut)                                // "Tuesday, March 3"
```

Predefined combinations:

```swift
launch.formatted(date: .long, time: .shortened)     // "March 3, 2026 at 4:05 PM"
launch.formatted(date: .abbreviated, time: .omitted) // "Mar 3, 2026"
launch.formatted(.iso8601)                           // "2026-03-03T13:05:00Z"
```

Relative to now:

```swift
let dayBefore = Date.now.addingTimeInterval(-86_400)
dayBefore.formatted(.relative(presentation: .named))    // "yesterday"
let numericAgo = Date.RelativeFormatStyle(presentation: .numeric)
dayBefore.formatted(numericAgo)                         // "1 day ago"
```

Ranges and countdowns:

```swift
let slot = launch..<launch.addingTimeInterval(5_400)
let meetingSpan = Date.IntervalFormatStyle().day().month().minute().hour()
slot.formatted(meetingSpan)   // "Mar 3, 4:05 - 5:35 PM" (ICU prints an en dash)

let untilDeparture = Date.now..<Date.now.addingTimeInterval(190_800)
let countdown = Date.ComponentsFormatStyle(style: .wide, fields: [.hour, .day])
untilDeparture.formatted(countdown)   // "2 days, 5 hours"
```

Related types: `Date.FormatStyle`, `Date.RelativeFormatStyle`,
`Date.IntervalFormatStyle`, `Date.ComponentsFormatStyle`.

### Relative to a chosen reference (iOS 18+)

`Date.AnchoredRelativeFormatStyle` describes one fixed date, the anchor,
relative to whatever moment you format. Plain `.relative` always measures from
the real current time; the anchored style lets you choose the reference, which
suits timelines, widgets and tests.

```swift
let meetup = Date(timeIntervalSince1970: 1_800_000_000)
let style = Date.AnchoredRelativeFormatStyle(anchor: meetup, presentation: .named)
style.format(meetup.addingTimeInterval(86_400))   // "yesterday": the anchor was a day before the reference
style.format(meetup.addingTimeInterval(-3_600))   // "in 1 hour"
```

## Durations

A `Duration` (iOS 16+) can be shown as a clock reading with
`Duration.TimeFormatStyle` or as labeled units with `Duration.UnitsFormatStyle`.

```swift
let ride = Duration.seconds(7_384)                  // 2 h 3 min 4 s
ride.formatted(.time(pattern: .hourMinuteSecond))   // "2:03:04"
ride.formatted(.time(pattern: .hourMinute))         // "2:03"
ride.formatted(.time(pattern: .minuteSecond))       // "123:04" (minutes are not wrapped into hours)

let stopwatch = Duration.TimeFormatStyle.Pattern.minuteSecond(padMinuteToLength: 2, fractionalSecondsLength: 2)
Duration.milliseconds(3_750).formatted(.time(pattern: stopwatch))   // "00:03.75"
```

```swift
let clock: Set<Duration.UnitsFormatStyle.Unit> = [.hours, .minutes, .seconds]
ride.formatted(.units(allowed: clock, width: .abbreviated))                      // "2 hr, 3 min, 4 sec"
ride.formatted(.units(allowed: clock, width: .wide, maximumUnitCount: 1))        // "2 hours"

let rest = Duration.seconds(150)
rest.formatted(.units(allowed: [.minutes, .seconds], width: .wide))     // "2 minutes, 30 seconds"
rest.formatted(.units(allowed: [.minutes, .seconds], width: .narrow))   // "2m 30s"
```

`maximumUnitCount` caps how many units appear.

## Measurements

```swift
let poolWater = Measurement<UnitTemperature>(value: 81, unit: .fahrenheit)
poolWater.formatted(.measurement(width: .wide))         // "81 degrees Fahrenheit"
poolWater.formatted(.measurement(width: .abbreviated))  // "81°F"
poolWater.formatted(.measurement(width: .narrow))       // "81°"
```

`usage:` lets the style convert to what the locale expects for that context:

```swift
let hike = Measurement<UnitLength>(value: 8, unit: .kilometers)
let roadSign = Measurement<UnitLength>.FormatStyle(width: .abbreviated, usage: .road)
hike.formatted(roadSign)   // "5 mi" in en_US, "8 km" in de_DE
```

The type is `Measurement<Unit>.FormatStyle`.

## Person names

`PersonNameComponents` holds `givenName`, `familyName`, `middleName`,
`namePrefix`, `nickname` and `nameSuffix`.

```swift
var person = PersonNameComponents()
person.namePrefix = "Dr."
person.givenName = "Ada"
person.familyName = "Lovelace"
person.nickname = "Addie"

person.formatted(.name(style: .long))         // "Dr. Ada Lovelace"
person.formatted(.name(style: .medium))       // "Ada Lovelace"
person.formatted(.name(style: .short))        // "Addie"
person.formatted(.name(style: .abbreviated))  // "AL"
```

The final order and form depend, in priority order, on the script of the name,
the user's preferences, the locale, and only then the style you asked for.

## Lists

```swift
let crew = ["Mina", "Omar", "Lea"]
crew.formatted(.list(type: .and))                     // "Mina, Omar, and Lea"
crew.formatted(.list(type: .or))                      // "Mina, Omar, or Lea"
crew.formatted(.list(type: .and, width: .narrow))     // "Mina, Omar, Lea"

let lanes = [3, 5, 8]
lanes.formatted(.list(memberStyle: IntegerFormatStyle<Int>(), type: .and))  // "3, 5, and 8"
```

The type is `ListFormatStyle`.

## Byte counts

```swift
let attachment: Int64 = 1_048_576
var labels: [String] = []
for style in [ByteCountFormatStyle.Style.memory, .file, .binary] {
    labels.append(attachment.formatted(.byteCount(style: style)))   // "1 MB" each time
}
```

`.memory` and `.binary` count in powers of 1024; `.file` and `.decimal` count
in powers of 1000. All four use the same unit labels ("KB", "MB"), never
"KiB" or "MiB", so a different base only shows once the value is large enough
for the rounding to differ.

## URLs

```swift
let guide = URL(string: "https://help.example.org/guides/setup?ref=home")!
guide.formatted()                                           // the full string
guide.formatted(.url.scheme(.never).host().path())          // "help.example.org/guides/setup"
guide.formatted(.url.scheme(.always).host().path(.never))   // "https://help.example.org"
guide.formatted(.url.scheme(.never).host(.never).path())    // "/guides/setup"
```

(Unwrap the literal URL with `guard let` in real code.)

## SwiftUI integration

Pass the value and the style to `Text` instead of building a string first:

```swift
Text(order.total, format: .currency(code: order.currencyCode))
Text(order.placedAt, format: .dateTime.day().month().hour().minute())
Text(workout.elapsed, format: .units(allowed: [.hours, .minutes], width: .abbreviated))
```

`Text` then formats with the view's `\.locale` environment value, so previews
and in-app locale overrides are respected, and the value stays typed until the
moment it is drawn. For live values:

```swift
Text(.now, style: .timer)                        // counts up from the date
Text(sessionStart, style: .relative)             // "2 min"
Text(timerInterval: sessionStart...sessionEnd)   // counts down across the range
```

`Text(timerInterval:)` needs iOS 16.

## Custom FormatStyle

Conform to `FormatStyle` and implement `format(_:)`. Add `ParseableFormatStyle`
if the text must also be read back. `FormatStyle` inherits `Codable` and
`Hashable`, so keep stored properties simple value types.

```swift
struct CompactCountStyle: FormatStyle {
    func format(_ count: Int) -> String {
        switch abs(count) {
        case 1_000_000...: scaled(count, by: 1_000_000) + "M"
        case 1_000...:     scaled(count, by: 1_000) + "K"
        default:           count.formatted()
        }
    }

    private func scaled(_ count: Int, by divisor: Double) -> String {
        (Double(count) / divisor).formatted(.number.precision(.fractionLength(0...1)))
    }
}

extension FormatStyle where Self == CompactCountStyle {
    static var compactCount: CompactCountStyle { CompactCountStyle() }
}

let followers = 48_700.formatted(.compactCount)   // "48.7K"
```

The static member in the constrained extension is what enables the
`.compactCount` dot syntax at call sites. (For real apps, `.notation(.compactName)`
already does this with localized suffixes; a custom style earns its place when
the rule is your own.)

## Common mistakes

| Mistake | Fix |
| --- | --- |
| `NumberFormatter` or `DateFormatter` in new code | `FormatStyle` (iOS 15+); Foundation caches the underlying formatters |
| String interpolation of a value inside `Text` | `Text(value, format:)` |
| Hardcoded `.locale(...)` for display | Leave it out so the user's locale applies |
| `.time(pattern:)` where labels are wanted | `.units(allowed:width:)` |
| A `Formatter` created in `body` or inside a loop | An inline style; it is cheap and cached |
| `DateComponentsFormatter` for a `Duration` | `Duration.TimeFormatStyle` or `Duration.UnitsFormatStyle` |
| Measurements formatted without `usage:` | Pass `.road`, `.person`, `.asProvided` or another usage that fits |

## Review checklist

- [ ] `FormatStyle` rather than `Formatter` subclasses when targeting iOS 15+
- [ ] `Text(_:format:)` rather than preformatted strings
- [ ] No hardcoded locale unless the output is machine-facing (for example, sent to a server)
- [ ] `Duration` values go through the time or units duration style
- [ ] Currencies are identified by ISO 4217 code ("EUR"), never by symbol ("€")
- [ ] Measurement display passes `usage:`
- [ ] Custom styles keep the `Codable` and `Hashable` conformance that `FormatStyle` requires working (value-type properties only)
- [ ] Output checked in `en_US`, `de_DE`, `ar_SA` and `ja_JP`

## References

- [FormatStyle](https://developer.apple.com/documentation/foundation/formatstyle)
- [IntegerFormatStyle](https://developer.apple.com/documentation/foundation/integerformatstyle)
- [FloatingPointFormatStyle](https://developer.apple.com/documentation/foundation/floatingpointformatstyle)
- [Date.FormatStyle](https://developer.apple.com/documentation/foundation/date/formatstyle)
- [Date.RelativeFormatStyle](https://developer.apple.com/documentation/foundation/date/relativeformatstyle)
- [Date.IntervalFormatStyle](https://developer.apple.com/documentation/foundation/date/intervalformatstyle)
- [Date.AnchoredRelativeFormatStyle](https://developer.apple.com/documentation/foundation/date/anchoredrelativeformatstyle)
- [Duration.TimeFormatStyle](https://developer.apple.com/documentation/swift/duration/timeformatstyle)
- [Duration.UnitsFormatStyle](https://developer.apple.com/documentation/swift/duration/unitsformatstyle)
- [Measurement.FormatStyle](https://developer.apple.com/documentation/foundation/measurement/formatstyle)
- [PersonNameComponents.FormatStyle](https://developer.apple.com/documentation/foundation/personnamecomponents/formatstyle)
- [ListFormatStyle](https://developer.apple.com/documentation/foundation/listformatstyle)
- [ByteCountFormatStyle](https://developer.apple.com/documentation/foundation/bytecountformatstyle)
- [URL.FormatStyle](https://developer.apple.com/documentation/foundation/url/formatstyle)
