Apple added something pretty neat to Foundation this year: Measurements. We can represent units, convert them to other units, compare them, and even convert them into formatted strings. Let's dive in.
It all starts with a Measurement.
let fuel = Measurement(value: 184, unit: UnitVolume.liters)
There are tons of different categories of units such as Volume, Mass, Speed, Power, Length, and many more.
Once created, a Measurement can be converted into any of other units in its category:
print(fuel.converted(to: .gallons))
// "8.18933748259766 gal"
We can also perform mathematical operations and comparisons on Measurements:
let tripLegA = Measurement(value: 1.4, unit: UnitLength.lightyears)
let tripLegB = Measurement(value: 2.3, unit: UnitLength.lightyears)
let tripTotal = tripLegA + tripLegB
print(tripTotal) // "3.7 ly"
print(tripLegA > tripLegB) // "false"
Last but certainly not least, we can nicely format a measurement into a String. Apple provides a MeasurementFormatter type that is fully locale-aware. This allows us to easily display Measurements in our apps in whichever ways our users expect.
let formatter = MeasurementFormatter()
formatter.locale = Locale(identifier: "en_US")
formatter.string(from: tripTotal)
// "21,751,587,607,342.14 mi"
formatter.locale = Locale(identifier: "fr")
formatter.string(from: tripTotal)
// "35 005 700 000 000 km"
Foundation is such a powerhouse of functionality, it can be easy to miss great new additions like this. Next time, we'll learn more about formatting Measurements for display in our apps.
Tweet
Share
on reddit