Grant Emerson

Battle of the Units

Battle of the Units — SwiftMoji Entry #19

Apple’s Foundation framework implements many of the components that are necessary to build great applications but not essential enough to be included in the Swift Standard Library. Two such components are the Measurement and Unit data structures which make code vastly more readable by encapsulating magic numbers – random numerical literals such as 4 or 1.7 within a codebase – in class variables with the appropriate naming conventions. They also handle conversion seamlessly and intuitively. The Measurement struct is initialized with a Double value and a UnitType. Due to the included implementation of all elementary mathematical operations, calculations such as multiplication can be done between two Measurements with the corresponding operator (*). In the code example, a temperature Measurement is created with the class variable Unit for Fahrenheit on UnitTemperature. The converted(to:) method is then called on this variable with an argument of UnitTemperature.celsius. The updated value is then read using the value property.

import Foundation

let 🇺🇸🧊 = Measurement(value: 13, unit: UnitTemperature.fahrenheit)
let 🇬🇧🧊 = 🇺🇸🧊.converted(to: UnitTemperature.celsius)

print("It's \(Int(🇺🇸🧊.value))ºF or \(Int(🇬🇧🧊.value))ºC outside! 🥶")
// It's 13ºF or -10ºC outside! 🥶
Tagged with: