Topics

#277: MeasurementFormatter Basics 📐📏

Topics

Today we're going to continue our look at the new Measurement functionality in Foundation. (Bite #276). MeasurementFormatter offers some great ways to format and print Strings of our Measurements. Let's take a look.

First we'll make define some units to work with. One of the most common ones we'll use in our apps is Length (for example when displaying how "far away" something is).

let distance = Measurement(value: 1.4, unit: UnitLength.kilometers)

Next, we'll make a formatter:

let formatter = MeasurementFormatter()

We'll leave the locale setting alone, which causes it to use the current locale of the device. In our case, en_US.

Finally, we'll print the formatted String.

print(formatter.string(from: distance))

Nice. Now we can start to try out some of the options. Let's start with the *style, we have three choices:

formatter.unitStyle = .short // "0.87mi"

formatter.unitStyle = .medium // (the default) "0.87 mi"

formatter.unitStyle = .long // "0.87 miles"

We'll use the .long style.

By default, our device locale being en_US is causing the distance to formatted with "miles" instead of "kilometers" (our input value). We can change this with unitOptions:

formatter.unitOptions = [.providedUnit]

// "1.4 kilometers"

We can even drop down and configure the NumberFormatter (Bite #182) that the MeasurementFormatter uses when formatting the numerical part of our Measurements:

measurementFormatter.numberFormatter.maximumFractionDigits = 0

// "1 mi"

Last but not least, we can ask the formatter for a String representing only the name of some unit:

let formatter = MeasurementFormatter()
formatter.string(from: UnitLength.lightyears)

// "light yrs"

Neat!

MeasurementFormatter is just another in a long list of wonderful little gems tucked away inside Foundation. Know of another that should be covered here? Send it along!.