Skip to content
A percentage type for Swift
Swift
Branch: master
Clone or download
Latest commit 3f646da Nov 13, 2019
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
.github
.swiftpm/xcode
Sources/Percent
Tests/PercentTests
.editorconfig Init Oct 1, 2019
.gitattributes Init Oct 1, 2019
.gitignore Init Oct 1, 2019
.travis.yml
Package.swift Init Oct 1, 2019
license
readme.md 0.2.0 Nov 13, 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.2.0")

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.