2.8 · Attributed strings, scanners, number formatters

Beyond plain String: text that carries styling, tools for pulling values out of text, and the formatters that turn numbers and quantities into words a person in any country will read correctly.

Mental model. Never format a number, a price or a list by hand. A formatter knows the locale’s rules, and you do not.

Attributed strings

Styled text as a value, and the UTF-16 detail that trips conversions.

  1. What is AttributedString, and how is it different from NSAttributedString? 2.8.1 · L2
    AttributedString (iOS 15) is the Swift-native styled text: a value type that holds characters plus attributes stored in runs (stretches that share the same…
  2. Why do ranges break when you move between String, AttributedString and NSAttributedString? 2.8.2 · L3
    Swift’s String and AttributedString use Range<String.Index> over characters. NSAttributedString, NSString and the text controls use NSRange over UTF-16 code…

Parsing text

Pulling numbers and words out of a string.

  1. When do you use Scanner, and how does it compare with Regex and split? 2.8.3 · L3
    Scanner is a stateful cursor that walks a string left to right, pulling out typed pieces: scanInt(), scanDouble(), scanCharacters(from:), scanUpToString(_:).…

Formatting numbers and quantities

Locale-aware output for numbers, money, sizes and lists.

  1. How do you format numbers, currency and percentages correctly? 2.8.4 · L2
    Use FormatStyle (value.formatted(.number), .currency(code:), .percent) or NumberFormatter. Both follow the locale: the decimal and grouping separators, the…
  2. Why shouldn’t you use Double for money, and what do you use instead? 2.8.5 · L2
    Double is a binary fraction, and most decimal fractions (0.1, 0.2) cannot be represented exactly in binary, so 0.1 + 0.2 == 0.3 is false. Errors are tiny, but…
  3. Which Foundation formatter replaces hand-written string code for sizes, lists, names and units? 2.8.6 · L2
    Foundation already localises many common outputs. ByteCountFormatter writes file sizes (“1 MB”). Measurement and MeasurementFormatter convert and print units…

More in Foundation & stdlib