Swift has more formatters than you think! 🤯
Hi 👋
Before we go into the topic of this email, I have a big thank you to my sponsor for a new week: Bitrise 🤖
Advertisement
Sponsors like Bitrise really help me grow my content creation, so if you have time please make sure to check out their survey: it’s a direct support to my content creation ☺️
If you have some experience with iOS, I’m pretty sure you’ve already used a DateFormatter
or a NumberFormatter
.
And you’ve probably noticed how much time these formatters save you versus if you’d had to write all the formatting logic by yourself!
But did you know that Swift has more formatters than just these two?
#01 – DateComponentsFormatter
As its name does suggest, DateComponentsFormatter
is a close relative of DateFormatter
.
But whereas DateFormatter
is great to format a point in time, DateComponentsFormatter
allows you to format quantities of time.
A typical use case would be to format the amount of time remaining before the end of a lengthy operation, like downloading a big file:
#02 – DateIntervalFormatter
Another close relative of DateFormatter
is DateIntervalFormatter
, which allows us to format user-facing pairs of dates.
It’s a less common use case, but any app that lets users schedule calendar events might find it pretty useful!
#03 – MeasurementFormatter
Dealing with physical units is a nightmare and it’s definitely not a topic that any iOS developer wants to spend their energy on.
So if your app displays any kind of physical measure to the user, you really want to make sure that you use MeasurementFormatter
.
This little gem will take care of automatically converting and displaying physical measures using the correct unit 👌
#04 – ByteCountFormatter
Displaying the size of a file seems easy enough, until you realize all the code that’s needed to choose the appropriate unit depending on the size!
(because no user wants to see a file size of 0.02GB or 1 000 000 KB 🥲)
And that’s when ByteCountFormatter
comes to the rescue:
#05 – PersonNameComponentsFormatter
Formatting a person’s name seems pretty straightforward: you write the given name, add a white space, write the family name, and that’s it…
…or is it? Because it turns out that not all regions of the world format a name following this convention!
For instance, Koreans write the family name first and the given name second.
And that’s when PersonNameComponentsFormatter
can help:
That’s it, we’ve completed our tour of Swift’s built-in formatters!
These additional formatters are definitely more niche than the more mainstream DateFormatter
or a NumberFormatter
…
…but the day you need one of them, it will definitely save you a lot of time and effort 😌
That’s all for this email, thanks for reading it!
If you’ve enjoyed it, feel free to forward it
to your friends and colleagues 🙌
I wish you an amazing week!
❤️