Skip to content

angelsolaorbaiceta/InkUnits

Repository files navigation

Alt InkUnits

InkUnits

Smart and lightweight unit conversion module written in Swift. InkUnits is responsible for all unit conversions behind InkStructure OSX app.

Basic Usage

Instantiate UnitConversionEngine:

let converter = UnitConversionEngine()

Then use the engine to make conversions:

try! converter.convert(25, from: "kg/m2", to: "g/cm2")

Yields:

2.5

You can make sure a given conversion can happen before attempting it:

if converter.canConvert(from: "N·cm", to: "kN·m")
{
    try! converter.convert(100, from: "N·cm", to: "kN·m")
}

Yields:

0.001

Alternatively, you can work with exceptions:

do
{
    try converter.convert(100, from: "N·cm", to: "kg/m")
}
catch UnitConversionError.inconsistentUnits(let sourceUnits, let targetUnits)
{
    print("Oops! couldn't convert from \(sourceUnits) to \(targetUnits)")
}

Prints:

"Oops! couldn't convert from N·cm to kg/m"

Or this other way:

do
{
    try converter.convert(100, from: "N·cm", to: "kg/m")
}
catch let error as UnitConversionError
{
    print(error.description)
}

Prints:

"Cannot convert from N·cm to kg/m"

See more in the documentation.

Installation

You can add InkUnits to your projects in one of the following ways:

Swift Package Manager

Add the following dependency in your Package.swift file:

dependencies: [
    .Package(url: "https://github.com/angelsolaorbaiceta/InkUnits.git", majorVersion: 1)
]

CocoaPods

TODO: add CocoaPods support.

Carthage

TODO: add Carthage support.

Currently Supported Units

For more details about how the configuration of InkUnits works and how to add more conversion factors, refer to Configuration.

Units that are currently present in the configuration are collected in the following table.

Magnitude Universal Units International Units US / Imperial Units
Time ms, s, min, h, day, week, month, year - -
Angle rad, deg - -
Length - mm, cm, dm, m, dam, hm, km mi, ft, in
Mass - mg, cg, dg, g, dag, hg, kg oz, lb
Force - N, kN, MN lbf

Note that, any compound unit using these simple ones will also be able to be converted by InkUnits, and there is where its power lies. For example, the following are understood by the conversion engine:

  • Area: cm2, m2, ft2...
  • Density: g/cm3, kg/m3, oz/ft3...
  • Moment: N·m, lbf·ft...

To add more unit conversion factors, see instructions in Configuration Documentation page.