Skip to content

About

Manipulate, compare, and convert any combination of physical quantities.

Resources

Stars

0 stars

Watchers

0 watching

Forks

 
 

Repository files navigation

Units 📏

Units is a Swift package to manipulate, compare, and convert between physical quantities. This package models measurements, which are a numerical value with a unit of measure. It has been designed so that users don't need to worry whether they are using a defined unit (like Newton) or a complex composite unit (like kg*m/s^2). Both should be easy to convert to and from different units, perform arithmetic operations, check dimensionality, or serialize to and from a string format.

This approach allows us to easily handle any permutation of units. You want to convert 12 km³/hr/N to ft²*s/lb? We've got you covered!

Included is a convenient command-line tool for performing quick unit conversions. See the CLI section for details.

Getting Started

To start using Units, import it to your project via the Package.swift file:

    dependencies: [
        .package(url: "https://github.com/NeedleInAJayStack/Units", from: "0.0.1"),

This package has no other dependencies.

Usage

Users should interact primarily with the Measurement struct. Here are a examples of arithmetic:

let drivingSpeed = 60.measured(in: .mile / .hour)
print(drivingSpeed.convert(to: .kilometer / .hour)) // Prints 96.56064 km/h

let drivingTime = 30.measured(in: .minute)
let drivingDistance = drivingSpeed * drivingTime
print(drivingDistance.convert(to: .mile)) // Prints 30 mi

Note that a measurement may be multiplied or divided by another measurement with any unit, resulting in a measurement that has a new-dimensioned unit (5 meters / 10 seconds ✅). However, addition and subtraction requires that both measurements have the same dimensionality (5 meters - 10 seconds ❌), otherwise a runtime error is thrown. If adding or subtracting two measurements with different units but the same dimensionality, the result retains the first measurement's unit (5 meters - 5 millimeters = 4.995 meters).

The type names in this package align closely with the unit system provided by Foundation. This was intentional to provide a familiar nomenclature for Swift developers. The APIs have been designed to avoid namespace ambiguity in files where both Units and Foundation are imported as much as possible. However, if an issue arises, just qualify the desired package like so:

let measurement = Units.Measurement(value: 5, unit: .mile)

Scalars

This package provides a special none unit that represents a unitless scalar measurement:

let unitless = 5.measured(in: .none)

Measurements whose arithmetic has cancelled out units are also represented as unitless:

let a = 6.measured(in: .meter) / 2.measured(in: .meter)
print(a.unit)  // Prints 'none'

Measurements are also representible through Int or Float scalars, which are automatically interpreted as unitless:

let m: Measurement = 6  // Has unit of 'none'

This allows including scalar values directly in arithmetic equations:

let distance: 5.measured(in: .meter) * 3 / 1.measured(in: .second)
print(distance)  // Prints '15 m/s'

Conversion

Only linear conversions are supported. The vast majority of unit conversions are simply changes in scale, represented by a single conversion coefficient, sometimes with a constant shift. Units that don't match this format (like currency conversions, which are typically time-based functions) are not supported.

Composite units are those that represent complex quantities and dimensions. A good example is horsepower, whose quantity is mass * length^2 / time^2.

Coefficients

Each quantity has a single "base unit", through which the units of that quantity may be converted. SI units have been chosen to be these base units for all quantities.

Non-base units require a conversion coefficient to convert between them and other units of the same dimension. This coefficient is the number of base units there are in one of the defined unit. For example, kilometer has a coefficient of 1000 because there are 1000 meters in 1 kilometer.

Composite units must have a coefficient that converts to the composte SI units of those dimensions. That is, horsepower should have a conversion to kilogram * meter^2 / second^2 (otherwise known as watt). This is natural for SI quantities and units, but care should be taken that a single, absolute base unit is chosen for all non-SI quantities since they will impact all composite conversions.

Constants

Units that include a constant value, such as Fahrenheit, cannot be used within composite unit conversions. For example, you may not convert 5m/°F to m/°C because its unclear how to handle their shifted scale. Instead use the non-shifted Kelvin and Rankine temperature units to refer to temperature differentials.

Serialization

Each defined unit must have a unique symbol, which is used to identify and serialize/deserialize it. Defined unit symbols are not allowed to contain the *, /, ^, or characters because those are used in the symbol representation of complex units. Complex units are represented by their arithmetic combination of simple units using * for multiplication, / for division, and ^ for exponentiation. Order of operations treats exponentiation first, and multiplication and division equally, from left-to-right. This means that, unless negatively exponentiated, units following a * can always be considered to be "in the numerator", and those following / can always be considered to be "in the denominator".

Here are a few examples:

  • kW*hr: kilowatt-hours
  • m/s: meters per second
  • m^2/s^2: square meters per square seconds
  • kg*m/s: kilogram-meters per second.
  • m/s*kg: equivalent to kg*m/s
  • m^1*s^-1*kg^1: equivalent to kg*m/s

Measurements are represented as the numeric value followed by the serialized unit with an optional space. For example, 5m/s or 5 m/s.

Expressions are a mathematical combination of measurements. Arithemetic operators, exponents, and sub-expressions are supported. Here are a few expression examples:

  • 5m + 3m
  • 5.3 m + 3.8 m
  • 5m^2/s + (1m + 2m)^2 / 5s

There are few expression parsing rules to keep in mind:

  • All parentheses must be matched
  • All measurement operators must have a leading and following space. i.e. *
  • Only integer exponentiation is supported
  • Exponentiated measurements must have parentheses to avoid ambiguity with units. i.e. (3m)^2

Default Units

For a list of the default units and their conversion factors, see the DefaultUnits.swift file

Custom Units

The unit system is backed by a Registry that maps unit symbols to their metadata. To add new units, use RegistryBuilder, and pass it to any operation that converts from a String to a Unit:

let registryBuilder = RegistryBuilder()
registryBuilder.addUnit(
    name: "centifoot",
    symbol: "cft",
    dimension: [.length: 1],
    coefficient: 0.003048 // This is the conversion to meters
)
let registry = registryBuilder.registry()
let centifoot = try Unit(fromSymbol: "cft", registry: registry)

let measurement = Measurement(value: 5, unit: centifoot)
print(5.measured(in: .foot).convert(to: centifoot))

This returns a Unit object that can be used in arithmetic, conversions, and serialization.

Encoding and Decoding

When using custom units, you must provide the custom registry to the encoder or decoder using userInfo:

let decoder = JSONDecoder()
decoder.userInfo[Unit.registryUserInfoKey] = registry  // Required to recognize custom units.
try decoder.decode(Unit.self, from: #""cft/s""#.data(using: .utf8))

Non-scientific Units

To measure quantities of a named thing — apples, cartons, people, flour — define a substance rather than adding units on the .amountOfSubstance dimension. Units sharing one dimension are interchangeable by definition, so apples and people defined that way would add together and cancel against one another without error. Each substance gets a dimension of its own instead. See Substances and Inventory.

Percent

While technically not a Measurement, the use of the percent symbol ('%') is still useful in conveying the "semanantics" of a scaler value so we include it in this package.

Here’s how math operators work with percentages in typical calculations:

Math operators with percentages treat the percent as its decimal equivalent (e.g., 25% = 0.25) but in the case of + and - the calculation is less direct.

Multiplication (100 * 25%)

When you multiply a number by a percentage, you’re finding that percent of the number. • 25% is the same as 0.25. • So, 100 * 25% = 100 * 0.25 = 25.

Division (100 / 30%)

Dividing by a percentage means dividing by its decimal form. • 30% is 0.3. • So, 100 / 30% = 100 / 0.3 ≈ 333.33.

Addition (100 + 10%)

Adding a percentage to a number is less direct, but usually means increasing the number by that percent. • 10% of 100 is 10. • So, 100 + 10% = 100 + (100 * 0.10) = 110.

General Rule

• Percent means “per hundred,” so 25% = 25/100 = 0.25. • Replace the percent with its decimal equivalent before performing the operation.

FormatStyle

The Measurement.Formatter provides the formatted method to enable the setting of the NumberFormatStyleConfiguration.Precision for String output.

Example Use:

    let measure = 28.123.measured(in: .meter)

    measure.formatted()  // -> "28.123 m"
    measure.formatted(minimumFractionDigits: 4)  // -> "28.1230 m"
    measure.formatted(maximumFractionDigits: 0)  // -> "28 m"
    measure.formatted(maximumFractionDigits: 1)  // -> "28.1 m"

Custom Dimensions

The built-in Quantity dimensions (.length, .mass, .time, etc.) cover the ISQ base quantities, but you can define your own dimension when none of them fit — for example, a Money dimension for cost calculations. Because Quantity is RawRepresentable, you can add one with a static extension:

extension Quantity {
    static let money = Quantity(rawValue: "Acme.Money")
}

Your dimension then behaves like any built-in one. Here a concrete rate of $/m^3 is multiplied by a volume in m^3, and the volume cancels to leave a pure cost:

let registry = try RegistryBuilder().addUnit(
    name: "dollar",
    symbol: "$",
    dimension: [.money: 1]
).registry()
let dollar = try Unit(fromSymbol: "$", registry: registry)

let rate = Measurement(value: 180, unit: dollar / .meter.pow(3)) // $180 per m^3
let volume = Measurement(value: 24, unit: .meter.pow(3))         // 24 m^3
print(rate * volume) // Prints '4320.0 $'

A dedicated dimension is safer than repurposing an unrelated base quantity such as .amountOfSubstance, which would silently cancel against unrelated units that share it. But the rawValue namespace is global: a Quantity is identified solely by its raw string, across every module linked into the program. If two modules each define a dimension with the same raw value — say both use "Money" — they are treated as the same dimension and will silently cancel against each other, producing wrong results with no error. There is no central registry to detect the clash.

To avoid this, namespace every custom rawValue with a prefix unique to your module or organization (e.g. "Acme.Money", not "Money"), exactly as the example above does. Reserve bare names like "Money" for nothing, since you cannot know what another dependency has chosen.

Substances and Inventory

A Substance is a named material, good, or kind of thing that quantities can be measured in — apple, flour, pie. Each one occupies a Quantity dimension of its own, so the dimensional analysis the package already performs is what keeps different substances apart:

let substances = try SubstanceRegistryBuilder()
    .define("apple", countable: true, measures: ["carton": 48], bridges: ["150 g/apple"])
    .define("person", countable: true)
    .registry()

let apple = try substances.require("apple")
let person = try substances.require("person")

let harvest = apple.measure(288)
let workforce = person.measure(4)

try harvest + workforce   // throws UnitError.incompatibleUnits — apples are not people

Measures

Declared measures are extra units on the substance's own dimension, so they convert freely within it. Their symbols are namespaced by the substance, since a carton of apples is not a carton of oranges:

let carton = apple.unit("carton")!   // symbol "apple.carton"
print(try harvest.convert(to: carton))             // Prints '6.0 apple.carton'

Because they share a dimension, quantities in different measures of one substance add directly, and the result keeps the first operand's unit:

let loose = apple.measure(96)
let packed = apple.measure(2, in: "carton")!
print(try loose + packed)   // Prints '192.0 apple'

Bridges

A bridge crosses out of a substance's dimension: it answers "what does an apple weigh?" A bridge is a rate with the substance in its denominator, so applying it is ordinary multiplication and the substance cancels:

print(try harvest.convert(to: .kilogram, via: substances))   // Prints '43.2 kg'

The same mechanism serves pack weight (kg/each), density (g/mL), and molar mass — one unit of a chemical substance being one mole of it:

let chemicals = try SubstanceRegistryBuilder()
    .define("water", bridges: ["18.015 g/water", "1 mol/water"])
    .registry()
let water = try chemicals.require("water")

print(try water.measure(2).convert(to: .gram, via: chemicals))   // Prints '36.03 g'

convert(to:via:) follows chains of bridges in either direction, so a substance defined only in terms of another still reaches mass:

let bakery = try SubstanceRegistryBuilder()
    .define("apple", bridges: ["150 g/apple"])
    .define("pie", bridges: ["6 apple/pie"])
    .registry()
let pie = try bakery.require("pie")

print(try pie.measure(2).convert(to: .gram, via: bakery))   // Prints '1800.0 g' (pie -> apple -> g)

When the two units already share a dimension, convert(to:via:) is exactly convert(to:), so it is always safe to reach for when a substance may be involved.

Counting

Quantity.count is a substance-free count, with the units each (ea), pair, dozen (dz), and gross (gr). It is deliberately separate from .amountOfSubstance, so counting items never cancels against a chemical quantity:

print(try 2.measured(in: .dozen).convert(to: .each))   // Prints '24.0 ea'
try 1.measured(in: .dozen) + 1.measured(in: .mole)     // throws — a dozen is not a mole

A substance declared countable: true is given a bridge to each automatically, so its holdings can be totalled as a plain count. A count on its own cannot become a mass, though — each does not say each of what:

print(try apple.measure(2, in: "carton")!.convert(to: .each, via: substances))  // Prints '96.0 ea'
try 96.measured(in: .each).convert(to: .gram, via: substances)   // throws SubstanceError.noBridge

Defining substances from content files

SubstanceManifest is Decodable, which is the primary way to define substances when they are data rather than code:

{
  "substances": [
    { "id": "apple", "name": "Granny Smith", "countable": true,
      "measures": { "carton": 48 }, "bridges": ["150 g/apple"] },
    { "id": "flour", "measures": { "sack": 25000 }, "bridges": ["1 g/flour"] }
  ]
}
let manifest = try JSONDecoder().decode(SubstanceManifest.self, from: data)
let substances = try SubstanceRegistryBuilder().add(manifest).registry()

Bridges are parsed after every unit has been minted, so a bridge may refer to a substance defined later in the same manifest.

Inventory

An Inventory holds at most one quantity per substance, so adding merges rather than appends — and because every measure of a substance shares its dimension, merging converts rather than failing:

var stock = Inventory()
try stock.add(apple.measure(96))
try stock.add(apple.measure(2, in: "carton")!)
print(stock[apple]!)   // Prints '192.0 apple'
print(stock.count)     // Prints '1' — the number of substances held

Removing more than is held throws, rather than silently going negative. Pass allowingNegative: true to model a debt or backorder. A holding that reaches exactly zero is dropped:

try stock.remove(apple.measure(500))                          // throws .insufficient
try stock.remove(apple.measure(500), allowingNegative: true)  // -308.0 apple

Bridges let a whole inventory be totalled in a common unit, across substances that have nothing else in common:

let pantry = try Inventory([apple.measure(10), flour.measure(500)])
print(try pantry.total(in: .gram, via: substances))   // Prints '2000.0 g'

total throws SubstanceError.noBridge if any single holding cannot reach the requested unit. Totalling in .each therefore requires every substance held to be countable — the pantry above cannot be counted, because flour is measured continuously rather than in items.

An inventory encodes as an array of its holdings, each substance recovered from its unit. Since substance units are minted at runtime, decoding needs the registry:

let decoder = JSONDecoder()
decoder.userInfo[Unit.registryUserInfoKey] = substances.units
let restored = try decoder.decode(Inventory.self, from: data)

Substances in composite units

A substance behaves like any other dimension, so it composes into rates. Here a picking rate is multiplied by a workforce; person cancels and apple survives, which is precisely what sharing a single dimension could not express:

let pickRate = 600.measured(in: apple.base / .day / person.base)
let weekly = try (person.measure(4) * pickRate)
    .convert(to: apple.unit("carton")! / .week)
print(weekly)   // Prints '350.0 apple.carton/week'

Substance dimensions are namespaced as Substance.<id>, so they cannot collide with the base quantities or with a dimension you define directly. The identifier is global across substances, though, exactly as described in Custom Dimensions — two manifests that both define "flour" describe the same substance.

CLI

The easiest way to install the CLI is with brew:

brew tap NeedleInAJayStack/tap
brew install units

Alternatively, you can build it from source and install it to /usr/local/bin/ using the install script. Note that swift must be installed, and you need write permissions to /usr/local/bin/.

./install.sh

To uninstall, run:

./uninstall.sh

Convert

You can then perform unit conversions using the unit convert command:

unit convert 5m/s mi/hr  # Returns 11.184681460272012 mi/hr

This command uses the unit and expression serialization format. Note that for convenience, you may use an underscore _ to represent the normally serialized space. Also, * characters may need to be escaped.

You can also evaulate math in the first argument. For example:

unit convert "60mi/hr * 30min" "mi"  # Returns 30.0 mi

List

To list the available units, use the unit list command:

unit list

Contributing

Contributions are absolutely welcome! If you find yourself using a custom unit a lot, feel free to stick it in an MR, and we can add it to the default list!

About

Manipulate, compare, and convert any combination of physical quantities.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages