---
title: "#276: Measurement Basics 📏📐"
url: https://littlebitesofcocoa.com/276-measurement-basics
author: Jake Marsh
published: 2016-10-17
topics: ["Foundation"]
description: "Apple added something pretty neat to Foundation this year: Measurements. We can represent units, convert them to other units, compare them, and even convert..."
---

# #276: Measurement Basics 📏📐

By Jake Marsh, October 17, 2016. HTML: https://littlebitesofcocoa.com/276-measurement-basics

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`.

``` swift
let fuel = Measurement(value: 184, unit: UnitVolume.liters)
```

There are <i>tons</i> 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:

``` swift
print(fuel.converted(to: .gallons))
// "8.18933748259766 gal"
```

We can also perform mathematical operations and comparisons on `Measurements`:

``` swift
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.

``` swift
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**.

<p></p>
