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.
- What is AttributedString, and how is it different from NSAttributedString?
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… - Why do ranges break when you move between String, AttributedString and NSAttributedString?
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.
- When do you use Scanner, and how does it compare with Regex and split?
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.
- How do you format numbers, currency and percentages correctly?
Use FormatStyle (value.formatted(.number), .currency(code:), .percent) or NumberFormatter. Both follow the locale: the decimal and grouping separators, the… - Why shouldn’t you use Double for money, and what do you use instead?
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… - Which Foundation formatter replaces hand-written string code for sizes, lists, names and units?
Foundation already localises many common outputs. ByteCountFormatter writes file sizes (“1 MB”). Measurement and MeasurementFormatter convert and print units…
More in Foundation & stdlib
- 2.1 · Collections, indexing, Sequence and lazy
- 2.2 · Date, Calendar, Locale, TimeZone, FormatStyle
- 2.3 · URL, URLComponents, Data, FileManager
- 2.4 · NotificationCenter, KVO and Operation
- 2.5 · JSON coder options, property lists, UserDefaults
- 2.6 · Bundle, resources, localization tables
- 2.7 · NSCache and locks
- 2.9 · Bridging to Objective-C Foundation types