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).

nshipster.com/formatter/

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:

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: