Discover MeasurementFormatter


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 🍿


Have you ever heard of a type called MeasurementFormatter?

If you need to display any kind of physical measure in your app, this type can be quite a big help!

Let me show you how!

Have a look at this code: I’m displaying a distance:

As you can see, the unit in which the distance is displayed has been hardcoded.

For users that are accustomed to the metric system, this code will be fine.

But for an American user that’s used to the imperial system, this would feel very weird and very confusing!

And that’s when MeasurementFormatter comes into play 😌

First, we need to turn our numerical value into a Measurement:

That Measurement will store both the numerical value, but also the unit in which it is expressed.

Then we can create a MeasurementFormatter and use it to display the Measurement we’ve just created:

Right now my Locale is set to French, so the distance is still displayed in kilometers.

You can notice, however, that the decimal separator has changed from a point to comma, because that’s how a French user expects a distance to be formatted.

And now if I manually set the Locale to American English, we can see some changes!

First, the decimal separator went back to being a point.

But, more importantly, the distance has automatically been converted from kilometers to miles!

So remember: any time you need to show physical measurements to your users, you definitely want to use a MeasurementFormatter: it will make the user experience much better and it won’t add too much complexity 👌

That’s all for this article, I hope you’ve enjoyed it!

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

import Foundation

let distanceInKiloMeters = 1.2

// Distance is 1.2 km
print("Distance is \(distanceInKiloMeters) km")

let measurement = Measurement(
    value: distanceInKiloMeters,
    unit: UnitLength.kilometers
)

let formattter = MeasurementFormatter()

formattter.locale = Locale(identifier: "en_US")

// Distance is 0.746 mi
print("Distance is \(formattter.string(from: measurement))")
Previous
Previous

I can teach you Combine in just 4 hours 😌

Next
Next

How about 5 new tips you can start using today? 💡