Skip to content
A percentage type for Swift
Swift
Branch: master
Clone or download
Latest commit 5f650f1 Oct 3, 2019
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
.github Init Oct 1, 2019
.swiftpm/xcode Add more readme examples and 100% test coverage Oct 1, 2019
Sources/Percent Add missing import Oct 3, 2019
Tests/PercentTests Add test and readme for Codable Oct 2, 2019
.editorconfig Init Oct 1, 2019
.gitattributes Init Oct 1, 2019
.gitignore Init Oct 1, 2019
.travis.yml Init Oct 1, 2019
Package.swift Init Oct 1, 2019
license Init Oct 1, 2019
readme.md 0.1.1 Oct 3, 2019

readme.md

Percent Build Status

A percentage type for Swift

Makes percentages more readable and type-safe, for example, for APIs that currently accept a fraction Double.

-.opacity(0.45)
+.opacity(45%)

Install

SwiftPM:

.package(url: "https://github.com/sindresorhus/Percent", from: "0.1.1")

Or just copy-paste it.

Usage

See the source for docs.

import Percent

10% + 5.5%
//=> 15.5%

-10% / 2
//=> -5%

(40% + 93%) * 3
//=> 399%

30% > 25%
//=> true

50%.of(200)
//=> 100

Percent(50)
//=> 50%

Percent(fraction: 0.5)
//=> 50%

50%.fraction
//=> 0.5

10%.rawValue
//=> 10

print("\(1%)")
//=> "1%"

The type conforms to Hashable, Codable, RawRepresentable, Comparable, and supports all the arithmetic operators.

Codable

The percent value is encoded as a single value:

struct Foo: Codable {
	let alpha: Percent
}

let foo = Foo(alpha: 1%)
let data = try! JSONEncoder().encode(foo)
let string = String(data: data, encoding: .utf8)!

print(string)
//=> "{\"alpha\":1}"

FAQ

Can you support Carthage and CocoaPods?

No, but you can still use SwiftPM for this package even though you mainly use Carthage or CocoaPods.

Related

You can’t perform that action at this time.