Tuesday, March 22, 2022

Swift FormatStyle Deep Dive

Brett Ohland (via Dave Verwer):

Apple introduced the new FormatStyle protocol with iOS 15. It allows for some truly remarkable things to happen when you’re converting your data into localized strings.

In true Apple fashion though, details about how to use these new features are lightly documented with few examples.

The breadth and depth that this new functionality has been added to Swift is really nice, Apple has added support for it on nearly all data types in Swift. You also have the ability to create custom FormatStyle implementations that allow you to arbitrarily convert types using this functionality.

He has lots of examples and explanations of what the different options do, in a whole series of posts that’s basically a Missing Manual.


Update (2022-06-06): Brett Ohland:

I recently expanded and revamped my FormatStyle deep-dive you linked to back in May into it’s own single-serving site.

Following the grand tradition, it’s fuckingformatstyle.com (or goshdarnformatstyle.com) and it has details on every style with every possible option.


3 Comments RSS · Twitter

// Lists
["Alba", "Bruce", "Carol", "Billson"].formatted() // "Alba, Bruce, Carol, and Billson"

I wonder if the Oxford comma in that formatting is localised or not. Or if it were even a conscious choice.

Funny enough, I noticed this too while I was writing the posts (but didn't publish it). The inclusion of the Oxford comma is very deliberate.

Iterating through every English localization, I noticed that the Oxford comma is used in every locale except for the UK and Australia.

letters.formatted(.list(type: .and).locale(Locale(identifier: "en_GB"))) // "a, b, c and d"
letters.formatted(.list(type: .and).locale(Locale(identifier: "en_AU"))) // "a, b, c and d"
letters.formatted(.list(type: .and).locale(Locale(identifier: "en_US"))) // "a, b, c, and d"
letters.formatted(.list(type: .and).locale(Locale(identifier: "en_CA"))) // "a, b, c, and d"
letters.formatted(.list(type: .and).locale(Locale(identifier: "en_NZ"))) // "a, b, c, and d"

Why? Who knows.

That's very cool. I think it's certainly the case that the Oxford comma is less prevalent in UK and Australian writing conventions than in the US.

Leave a Comment