David Yang

Tips and posts for iOS developers from an iOS developer.

Measurement is a powerful tool available on all Apple OS and a must-use when having to deal with values such as temperature, pressure, speed, area, etc.

Definition

It is a generic structure (object if you’re using NSMeasurement) that represents a numeric quantity labeled with a unit of measure.

The nice things about it

It’s easy to declare

let celsius = Measurement(value: Double(15), unit: UnitTemperature.celsius)
print(celsius)

Output:

15.0 °C

You can work with unit conversion

let celsius = Measurement(value: Double(15), unit: UnitTemperature.celsius)
let fahrenheit = celsius.converted(to: UnitTemperature.fahrenheit)
print(fahrenheit)

Output:

58.99999999999578 °F

You can do operations on it

let a = Measurement(value: Double(15), unit: UnitTemperature.celsius)
let b = Measurement(value: Double(15), unit: UnitTemperature.celsius)
let c = a + b
print(c)

Output:

30.0 °C

Or even:

let a = Measurement(value: Double(15), unit: UnitTemperature.celsius)
let b = a * 2
print(b)
let c = b.converted(to: UnitTemperature.fahrenheit)
print(c)

Output:

30.0 °C
85.99999999999557 °F

You have a formatter

let a = Measurement(value: Double(15), unit: UnitTemperature.celsius)
let b = a.converted(to: UnitTemperature.fahrenheit)
print(b)

let formatter = MeasurementFormatter()
formatter.numberFormatter.maximumFractionDigits = 2
let fahrenheihtString = formatter.string(from: b)
print(fahrenheihtString)

Output:

58.99999999999578 °F
59°F

You can deal with all these kinds of measure unit

Physical Dimension:

  • UnitArea
  • UnitVolume
  • UnitAngle

Mass, Weight, and Force:

  • UnitMass
  • UnitPressure

Time and Motion:

  • UnitAcceleration
  • UnitDuration
  • UnitFrequency
  • UnitSpeed

Energy, Heat, and Light:

  • UnitEnergy
  • UnitPower
  • UnitTemperature
  • UnitIlluminance

Electricity:

  • UnitElectricCharge
  • UnitElectricCurrent
  • UnitElectricPotentialDifference
  • UnitElectricResistance

Concentration and Dispersion

  • UnitConcentrationMass
  • UnitDispersion

Fuel Efficiency:

  • UnitFuelEfficiency

Links

The Official Apple Documentation: https://developer.apple.com/documentation/foundation/units_and_measurement