ListFormatter: The Missing Documentation
Difficulty: Beginner | Easy | Normal | Challenging
From iOS 13 Apple made a ListFormatter available — but skimped rather on the documentation. Hopefully this rather short article can help you out!
This article has been developed using Xcode 12.0, and Swift 5.3
The problem to be solved
We have three names, and we wish to write these as a list separated with commas.
In Swift we have the
let names = [“Livesh”, “Romesh”, “Chau”, “Bella”]
and I would like a **sample output** of
Livesh, Romesh, Chau, and Bella
So how can I achieve this?
There are two ways, I’ll call one the old way, and one the ListFormatter way.
The Old Way
I’ll need to know how many elements there are in an Array, and process a new String.
This is a little bit tricky, I’m checking to see if I’m at the end of the array and appending the correct element (whether it contains and or a comma) — it’s all a little — shall we say, not ideal.
The new way
If you’re using iOS 13 onwards you can use the following:
let namesString = ListFormatter.localizedString(byJoining: names)
and that’s it! That produces the output as expected
Changing the locale
I’m currently in the UK and want to define my locale as such.
That’s fine; ListFormatter has you covered!
In this example I’ll set the locale as
Which prints the substantively different output as
Livesh, Romesh, Chau and Bella (note that it is the final comma that is missing, and this is a function of the locale that I’ve picked!).
There is a rather natty option we can use to create lovely lists. What about…
this outputs properly formatted currency in a list:
£1.30, £1.20, £9.40 and £3.40
Which in this case is £, since the currency chosen is
Now we have learnt that trick, can we do the same with dates?
You certainly can!
This gives the following output:
21 September 2027, 16 September 2008 and 12 November 1992
Which is extremely nice.
There are so many different formatters we can use, and using ListFormatter will allow you to produce readable Strings for your user which is of course nice.
Making things easer for the user? Isn’t that why we all got into this game?
Thanks for reading! If you want the code from this article then you can look it up in my repo.
If you’ve any questions, comments or suggestions please hit me up on Twitter