Formatter
Formatter’s origins trace back to NSCell, which is used to display information and accept user input in tables, form fields, and other views in AppKit. Much of the API design of (NS)Formatter reflects this.
Back then, formatters came in two flavors: dates and numbers. But these days, there are formatters for everything from physical quantities and time intervals to personal names and postal addresses. And as if that weren’t enough to keep straight, a good portion of these have been soft-deprecated, or otherwise superseded by more capable APIs (that are also formatters).
The article explores the Formatter
class in Swift’s Foundation framework, essential for transforming data into human-readable formats, addressing complexities like user language, calendar, and currency preferences.
It categorises formatters into four groups:
- Numbers and Quantities (
NumberFormatter
for styles like decimal or currency,MeasurementFormatter
for units like speed) - Dates, Times, and Durations (
DateFormatter
for customisable date/time,ISO8601DateFormatter
,DateComponentsFormatter
,DateIntervalFormatter
, andRelativeDateTimeFormatter
for relative expressions like “yesterday”) - People and Places (
PersonNameComponentsFormatter
for culturally sensitive names,CNPostalAddressFormatter
for addresses) - Lists and Items (
ListFormatter
for locale-aware list joining)
NumberFormatter
handles diverse number styles and rounding, while MeasurementFormatter
uses type-safe units, both leveraging locale awareness.
DateFormatter
and its siblings offer flexible date/time formatting, with RelativeDateTimeFormatter
enhancing user-friendly outputs. PersonNameComponentsFormatter
and CNPostalAddressFormatter
manage complex name and address formatting, with the latter supporting attributed strings for component highlighting. ListFormatter
simplifies list formatting with locale-specific separators.
The article emphasises Swift’s clear syntax and safety in utilising these formatters, encouraging developers to consolidate formatting logic into custom Formatter
subclasses for maintainability.
Category:
Tag:
Year: