How to format a list in iOS 15 and macOS 12

How to format a list in iOS 15 and macOS 12

Today, I have an article about new list formatting that Apple introduced in iOS 15 (and other operating systems unveiled during WWDC 2021). It's a small but useful new feature, so without further ado, let's get started:

let list = ["apple"].formatted(.list(type: .or))

// apple

let list = ["apple", "banana"].formatted(.list(type: .or))

// apple or banana

let list = ["apple", "banana", "peach"].formatted(.list(type: .or))

// apple, banana, or peach

The new list style automatically adjusts formatting to the number of items in the list. If we have two items, they will be separated by a conjunction. If there are more items, they will be separated by commas, and the last item will also have the conjunction. We can specify the conjunction by setting the type argument. At the moment, we have to conjunction types .or and .and:

let list = ["apple", "banana", "peach"].formatted(.list(type: .and))

// apple, banana, and peach

We can also specify the width of the conjunction:

let list = ["apple", "banana", "peach"].formatted(.list(type: .or, width: .short))

// apple, banana, or peach

let list = ["apple", "banana", "peach"].formatted(.list(type: .and, width: .short))

// apple, banana, & peach

The width parameter defines how the conjunction will be displayed. This parameter works together with the list type. In the code above, for the .or type even with .short width, we still get the or conjunction. Where for the .and type, we get the & instead of the full and.  

Of course, the formatting will also depend on the user's Locale, but this is how it behaves for en_US.

The table below shows how different width options work with the list types:

Type / Width .standard .short .narrow
.or apple, banana, or peach apple, banana, or peach apple, banana, or peach
.and apple, banana, and peach apple, banana, & peach apple, banana, peach

Those are the basics of the list formatting, but that's not all we can do with it. There is one other parameter  - .memberStyle - which allows us to customize each individual value in the list:

let list2 = [25, 50, 75, 100].formatted(.list(memberStyle: .percent, type: .or))

// 25%, 50%, 75%, or 100%

For members, we can use all the format styles built into the SDK, like .dateTime or .currency(). If we need more customization, we can always create the custom style.

That's it. I hope this short article was helpful. If you liked it, please consider checking other articles related to formatting in iOS 15, like this one:

How to format a Date in iOS 15 and macOS 12 | This Dev Brain by Michal Tynior
Learn how to format a Date using the new APIs introduced in iOS 15 and macOS 12.

Comments

Anything interesting to share? Write a comment.