Unit conversion library for Swift.

Related tags

Utility MKUnits
Overview

MKUnits

Version Build Status Swift License Twitter

MKUnits is extremely precise unit conversion library for Swift. It provides units of measurement of physical quantities and simplifies manipulation of them.

NB For Objective-C implementation, please refer to MKUnits pod 2.2.1 or visit [archived branch][archive-branch]. [archive-branch]:https://github.com/michalkonturek/MKUnits/tree/archive-objc

License

MKUnits is available under the MIT license. See the LICENSE file for more info.

Installation

MKUnits is available through CocoaPods. To install it, simply add the following line to your Podfile:

pod "MKUnits"

Example

Let's create 1.5 kilograms [kg],

let kilograms = 1.5.kilogram()

0.5 [kg] in grams [g]

let grams = 500.gram()

and 10 pounds [lb] (which is 4.5359237 [kg])

let pounds = 10.pound()

Then we add all of the above togehter and subtract 0.0001 [kg] in milligrams [mg].

let milligrams = 100.milligram()
var result = kilograms + grams + pounds - milligrams

The result amount is 6.5358237 [kg].

Now we subtract 0.5358237 [kg] in ounces [oz], which is 18.900624805 [oz] according to Google converter, but as MKUnits is very precise, it is in fact 18.900624805483390296005199558361177 [oz].

let ounces = 0.5358237.kilogram().converted(MassUnit.ounce)
result = result - ounces

The result amount is ~6 [kg]; 6.00000000000000000000000000000000003 [kg] to be exact.

Now we want the result to be in stones [st], so:

result = result.converted(MassUnit.stone)
// 0.94483873964811055873038869091017890993 st

As the result is too precise for our needs, we want to round it.

let rounded = result.rounded(3)
// 0.945 st

Supported Units

At the moment MKUnits supports the following group units:

  • Area (base unit: square meter)
  • Mass (base unit: kilogram)
  • Length (base unit: meter)
  • Time (base unit: second)
  • Volume (base unit: litre)

You can easily extend MKUnits by adding new group units or units.

Extending MKUnits

Adding a new group unit

To add a new group unit, simply create a class that extends Unit and follow the convention below.

Please make sure that unit symbols are unique across your new group unit.

public final class NewUnit: Unit {

    public static var unitA: NewUnit {
        return NewUnit(
            name: "unit A",
            symbol: "uA",
            ratio: NSDecimalNumber.one() // as it is a base unit
        )
    }
    
    public static var unitB: NewUnit {
        return NewUnit(
            name: "unit B",
            symbol: "uB",
            ratio: NSDecimalNumber(mantissa: 2, exponent: 0, isNegative: false)
        )
    }
}

extension NSNumber {

    public func unitA() -> Quantity {
        return Quantity(amount: self, unit: NewUnit.unitA)
    }
    
    public func unitB() -> Quantity {
        return Quantity(amount: self, unit: NewUnit.unitB)
    }
}

Adding new units to existing group unit

To add additional units to existing group unit simply create a category for that group unit.

Do not sublcass as units are only interconvertible with units belonging to the same group unit.

extension NewUnit {
    public static var unitC: NewUnit {
        return NewUnit(
            name: "unit C",
            symbol: "uC",
            ratio: NSDecimalNumber(mantissa: 4, exponent: 0, isNegative: false)
        )
    }
}

extension NSNumber {
    public func unitC() -> Quantity {
        return Quantity(amount: self, unit: NewUnit.unitC)
    }
}

Contributing

  1. Fork it.
  2. Create your feature branch (git checkout -b new-feature).
  3. Commit your changes (git commit -am 'Added new-feature').
  4. Push to the branch (git push origin new-feature).
  5. Create new Pull Request.
Comments
  • Proposal: Add NSNumber category.

    Proposal: Add NSNumber category.

    You can make code more readable, if you'll make a category for NSNumber for units, so id kilograms = [MKQuantity mass_kilogramWithAmount:@1.5]; you can write as id kilograms = (@1.5).mass_kilogram;

    type-enhancement status-accepted 
    opened by shmidt 4
  • Correct the spelling of CocoaPods in README

    Correct the spelling of CocoaPods in README

    This pull requests corrects the spelling of CocoaPods 🤓 https://github.com/CocoaPods/shared_resources/tree/master/media

    Created with cocoapods-readme.

    opened by ReadmeCritic 3
  • Update dependency on MKFoundationKit to 1.3.x

    Update dependency on MKFoundationKit to 1.3.x

    Pod outdated says:

    • MKFoundationKit 1.2.3 -> (unused) (latest version 1.3.0)

    It would be nice to get the dependency up to date.

    Thanks for a really useful library!

    type-enhancement status-accepted 
    opened by weibel 2
  • 'Unit' class conflicts with iOS 10's 'Unit' class from NSMeasurement.

    'Unit' class conflicts with iOS 10's 'Unit' class from NSMeasurement.

    This issue arises when extending MKUnits, for example:

    public final class TemperatureUnit: Unit {
      
      public static var kelvin: TemperatureUnit {
        return TemperatureUnit(
          name: "kelvin",
          symbol: "K",
          ratio: NSDecimalNumber.one // base unit
          
        )
      }
      
    }
    

    Produces a compiler error: 'Unit' is only available on iOS 10.0 or newer. (Swift 3, Xcode 8.1)

    type-discussion 
    opened by cjmconie 1
  • Added: US Short Ton

    Added: US Short Ton

    Added the US Short Ton to MKMassUnit+Imperial. The symbol is technically “t”, but that’s being used by Metric Ton, so I set it to “tn” to avoid confusion. I also considered “ust”, “USt”, and “ton”. If anyone has a better symbol for it, please change it.

    opened by glowcap 1
  • Using MKUnits for OS X with CocoaPods

    Using MKUnits for OS X with CocoaPods

    I am sure I can integrate it by hand but if I try to use MKUnits in an OS X application: The platform of the target ... (OS X 10.10) is not compatible withMKUnits (2.0.0)which has a minimum requirement of iOS 7.0.

    type-discussion 
    opened by edasque 1
  • Added Energy unit (+tests, example).

    Added Energy unit (+tests, example).

    Added new unit - Energy, containing cal, kcal, J, kJ, MJ, GJ (values based on http://www.unitjuggler.com/convert-energy-from-J-to-kJ.html). Extended tests and example to cover new feature.

    type-enhancement status-accepted 
    opened by natalia-osa 1
  • REQUEST: Serialization and string conversion (examples)

    REQUEST: Serialization and string conversion (examples)

    Awesome library. I love the way it's built, and the philosophy of ease of use. Clearly lots of thought has gone into this.

    At present, there's no obvious way to parse a string and obtain the relevant units object, right? To do so would require extra type conversion methods on the MKUnit class, much in the same spirit as what NSNumber class does for all number types (e.g. boolValue, intValue etc.). These might be called timeQuantity or asMass or whatever.

    Well, I'd like to use this in an real app, and am interested in persisting MKUnits in two ways:

    Since both make use of NSValueTransformer it might make sense to supply an implementation that converts MKQuantity to and from NSString, or alternatively, NSData.

    type-enhancement status-under-review 
    opened by fatuhoku 1
  • NSDecimalNumber on watchOS

    NSDecimalNumber on watchOS

    It looks like NSDecimalNumber().multiplying(by: NSDecimalNumber) returns -1 on watchOS.

    Reproducible sample to convert a number from square foot to square meter:

    let squareFootRatio = NSDecimalNumber(mantissa: 9290304, exponent: -8, isNegative: false) // 0.09290304
    NSDecimalNumber(value: 446).multiplying(by: squareFootRatio) // -1, expected: 41.43475584
    
    opened by iosdeveloper 0
Owner
Michal Konturek
Michal Konturek
This package will contain the standard encodings/decodings/hahsing used by the String Conversion Tool app.

This package will contain the standard encodings/decodings/hahsing used by the String Conversion Tool app. It will also, however, contain extra encoding/decoding methods (new encoding/decoding)

Gleb 0 Oct 16, 2021
Unit converter in Swift

Scale ❤️ Support my app ❤️ Push Hero - pure Swift native macOS application to test push notifications PastePal - Pasteboard, note and shortcut manager

Khoa 324 Dec 10, 2022
Project shows how to unit test asynchronous API calls in Swift using Mocking without using any 3rd party software

UnitTestingNetworkCalls-Swift Project shows how to unit test asynchronous API ca

Gary M 0 May 6, 2022
Testable Combine Publishers - An easy, declarative way to unit test Combine Publishers in Swift

Testable Combine Publishers An easy, declarative way to unit test Combine Publishers in Swift About Combine Publishers are notoriously verbose to unit

Albert Bori 6 Sep 26, 2022
Unit converter in Swift

Unit converter in Swift

Khoa 324 Jun 29, 2022
Cross-Platform, Protocol-Oriented Programming base library to complement the Swift Standard Library. (Pure Swift, Supports Linux)

SwiftFoundation Cross-Platform, Protocol-Oriented Programming base library to complement the Swift Standard Library. Goals Provide a cross-platform in

null 620 Oct 11, 2022
swift-highlight a pure-Swift data structure library designed for server applications that need to store a lot of styled text

swift-highlight is a pure-Swift data structure library designed for server applications that need to store a lot of styled text. The Highlight module is memory-efficient and uses slab allocations and small-string optimizations to pack large amounts of styled text into a small amount of memory, while still supporting efficient traversal through the Sequence protocol.

kelvin 4 Aug 14, 2022
macOS system library in Swift

SystemKit A macOS system library in Swift based off of libtop, from Apple's top implementation. For an example usage of this library, see dshb, a macO

null 323 Jan 5, 2023
Swift library to develop custom Alexa Skills

AlexaSkillsKit AlexaSkillsKit is a Swift library that allows you to develop custom skills for Amazon Alexa, the voice service that powers Echo. It tak

Claus Höfele 170 Dec 27, 2022
🏹 Bow is a cross-platform library for Typed Functional Programming in Swift

Bow is a cross-platform library for Typed Functional Programming in Swift. Documentation All documentation and API reference is published in our websi

Bow 613 Dec 20, 2022
Focus is an Optics library for Swift (where Optics includes Lens, Prisms, and Isos)

Focus Focus is an Optics library for Swift (where Optics includes Lens, Prisms, and Isos) that is inspired by Haskell's Lens library. Introduction Foc

TypeLift 201 Dec 31, 2022
A Swift micro library for generating Sunrise and Sunset times.

Solar A Swift helper for generating Sunrise and Sunset times. Solar performs its calculations locally using an algorithm from the United States Naval

Chris Howell 493 Dec 25, 2022
Plugin and runtime library for using protobuf with Swift

Swift Protobuf Welcome to Swift Protobuf! Apple's Swift programming language is a perfect complement to Google's Protocol Buffer ("protobuf") serializ

Apple 4.1k Dec 28, 2022
A Swift package for rapid development using a collection of micro utility extensions for Standard Library, Foundation, and other native frameworks.

ZamzamKit ZamzamKit is a Swift package for rapid development using a collection of micro utility extensions for Standard Library, Foundation, and othe

Zamzam Inc. 261 Dec 15, 2022
noppefoxwolf/notion is a notion.so API library written in swift.

notion noppefoxwolf/notion is a notion.so API library written in swift. Installation Xcode Project > Swift Packages [email protected]:noppefoxwolf/notion

noppefoxwolf 44 Oct 7, 2022
This library project contains a few noise generators created in Swift.

SwiftNoiseGenerator This library project contains a few noise generators created in Swift. contains: Perlin Noise Simplex Noise How to use Edit your P

Ichiro HIROTA 1 Jan 20, 2022
Angle is a simple Swift library that provides Angle structure representing angles.

Angle is a simple Swift library that provides Angle structure representing angles. It handles angles using circular measure by default but is al

Geonu Jeon 2 Nov 30, 2021
A library to manage NVRAM Stuff in Swift

libNVRAMSwift A Library to manage NVRAM Stuff, written in Swift. CLI Example utility here Library Usage Declare a new instance of the NVRAM Struct, fo

Serena 7 Sep 25, 2022
Support library of BudouX.swift to handle HTML

HTMLBudouX.swift HTMLBudouX.swift is a support library of BudouX.swift to handle HTML. Detail about BudouX.swift is here Usage You can translate an HT

griffin-stewie 1 Dec 31, 2021