Which Foundation formatter replaces hand-written string code for sizes, lists, names and units?

2.8.6 · L2 · Learning

Predict first

What does this print?

print(["a", "b", "c"].formatted(.list(type: .and).locale(Locale(identifier: "en_US"))))
  • a, b, c
  • a, b, and c
  • a b c

Predict first

What does this print?

print(ByteCountFormatter.string(fromByteCount: 1_000_000, countStyle: .file))
  • 1 MB
  • 976.6 KB
  • 1,000,000 bytes

Mental model. These formatters are a phrasebook. You say what you mean (“three items”), and it says it properly in each language.

Foundation already localises many common outputs. ByteCountFormatter writes file sizes (“1 MB”). Measurement and MeasurementFormatter convert and print units (1 km as 1000 m, or miles for a US user). ListFormatter and .list join items with the locale’s conjunction (“a, b, and c”). PersonNameComponentsFormatter orders given and family names by culture. RelativeDateTimeFormatter gives “2 hours ago”, and DateIntervalFormatter formats a range.

The rule is the same for all of them: pass the structured value (a byte count, a measurement, an array, name components), not a pre-built string, and let the formatter handle the language. Pin the locale in tests and for machine-readable output.

The English list style adds the conjunction and the serial comma. Other locales produce their own pattern.

The file style uses decimal units, so one million bytes is exactly 1 MB.

Common traps

  • Joining a list with ", " and an “and”. The conjunction and the serial comma are locale rules.
  • Displaying a name as “first last”. Many cultures put the family name first.

They might follow up with

  • Does ByteCountFormatter use 1,000 or 1,024? It depends on countStyle: .file is decimal on Apple platforms, .binary is 1,024.
  • Where do these live in the new API? Many have FormatStyle forms, such as .list(type:) and .measurement(width:).

Related questions

  • 2.8.4 How do you format numbers, currency and percentages correctly?
  • 2.2.7 FormatStyle or DateFormatter: which do you reach for?

← Why shouldn’t you use Double for money, and what do you use instead?