Units and Measurement Conversion in Swift (Part 1)
Most developers are not aware that Apple introduced the units and measurements APIs. They are part of the Foundation framework and available on every Apple platform.
Let’s get started by seeing what
Unitclass represents a unit that has a string to describe it called
Dimensionclass inherits from
- It has multiple subclasses, each representing a different dimension (e.g.
- Each of these subclasses defines a base unit and multiple additional units that can be converted to other units of the same dimension by using a
- A list of all dimension subclasses can be found in Apple’s documentation.
Measurementstruct wraps a double value together with a unit.
Now lets see how
If you’re 1,73 meters tall, you’d create a
Measurement instance like this:
let heightInMeters = Measurement(value: 1.73, unit: UnitLength.meters)
Then you can convert it to other units like this:
let heightInInches = heightInMeters.converted(to: UnitLength.inches)
You should see “28.7 in” in your output, showing that the conversion process has worked.
UnitLength class, like all unit subclasses, spans a huge range of units from old to futuristic. For example, you can convert feet to astronomical units, which is equal to the average distance between the Earth and the Sun, or about 150 million kilometers:
let heightAUs = heightInFeet.converted(to: UnitLength.astronomicalUnits)
Every unit works exactly the same as the one we’ve seen. Here are some more examples:
// Convert fahrenheit to celsius
let fahrenheit = Measurement(value: 6, unit: UnitTemperature.fahrenheit)
let celsius = fahrenheit.converted(to: .celsius)
// Convert kilometersPerHour to milesPerHour
let kilometersPerHour = Measurement(value: 35, unit: UnitSpeed.kilometersPerHour)
let milesPerHour = kilometersPerHour.converted(to: .milesPerHour)
As we have seen Swift provides an easy-to-use and powerful way of defining, using, and converting measurements.
Since there are currently 21 built-in dimensions with about 200 units combined, this will be enough for most apps. But there is also the possibility to define and add special units or even whole new dimensions. We will cover this in the next article.
Thanks for reading!
What are you thoughts about this? Tweet me @franceleonidev and share your opinion.
- Mobile App Development (276)