Bad practice: not using the modern formatting API


You’re more of a video kind of person? I’ve got you covered! Here’s a video with the same content than this article 🍿


Can you guess what’s wrong with this code?

At first glance the code seems completely fine…

…and the truth is that it actually is!

However, this code is also very much error prone.

It’s easy to misconfigure the formatter, for instance by mistakenly using uppercase characters in the dateFormat.

Also, because formatters are expensive to create, it’s also easy to forget to cache and re-use your them and then incur the negative cost in performances.

But did you know that since iOS 15 Apple has introduced a much simpler API to format values?

You actually don’t even need to create a formatter anymore, instead you just call the method .formatted() on the Date and it will return a String representation of this Date.

And of course, you can customize the way the date is formatted, either by using some presets for its date and time components.

Or by creating your own preset.

What’s great is that the code is now more much self descriptive and it’s become much harder to implement a wrong formatting by mistake!

And actually this new formatting API is not limited to dates, but can also be used with other type of values, like numbers or collections.

That’s all for this article, I hope that you’ve enjoyed discovering this new formatting API!

Here’s the code if you want to experiment with it:

// Before
import Foundation

let now = Date()
let formatter = DateFormatter()
formatter.dateFormat = "dd/MM/yyyy"

// 05/04/2024
formatter.string(from: now)

// After
import Foundation

let now = Date()

// 05/04/2024, 18:15
now.formatted()

// 05/04/2024
now.formatted(date: .numeric, time: .omitted)

// April 05
now.formatted(.dateTime​.day(.twoDigits)​.month(.wide))

// 0.420
0.42.formatted(
    .number.precision(.significantDigits(3))
)

// Option A, Option B, or Option C
[
    "Option A",
    "Option B",
    "Option C"
].formatted(.list(type: .or))
Previous
Previous

I can teach you the basics of SwiftData in 4 hours 👩🏽‍🎓👨🏻‍🎓

Next
Next

How to enable spell checking in Xcode