Skip to content

A percentage type for Swift

License

Notifications You must be signed in to change notification settings

sindresorhus/Percentage

Percentage

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

Add the following to Package.swift:

.package(url: "https://github.com/sindresorhus/Percentage", from: "3.0.0")

Or add the package in Xcode.

Usage

See the source for docs.

import Percentage

10% + 5.5%
//=> 15.5%

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

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

30% > 25%
//=> true

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

Percentage(50)
//=> 50%

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

Percentage.from(100, of: 200)
//=> 50%

Percentage.change(from: 100, to: 150)
//=> 50%

50%.fraction
//=> 0.5

10%.rawValue
//=> 10

50%.isWithinStandardRange
//=> true

150%.clamped(to: 0%...100%)
//=> 100%

110%.clampedZeroToHundred
//=> 100%

100.increased(by: 20%)
//=> 120

100.decreased(by: 20%)
//=> 80

40%.originalValueBeforeIncrease(finalValue: 120)
//=> 85.71428571428571

12%.originalValueBeforeDecrease(finalValue: 106)
//=> 120.45454545454545

90%.isPercentOf(67)
//=> 74.44444444444444

33.333%.formatted(decimalPlaces: 1)
//=> "33.3%"

// With locale (macOS 12.0+/iOS 15.0+)
50%.formatted(decimalPlaces: 1, locale: Locale(languageCode: .french))
//=> "50,0 %"

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

Percentage.random(in: 10%...20%)
//=> "14.3%"

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

SwiftUI and Cocoa overloads

Percentage overloads common SwiftUI and Cocoa APIs that accept a fraction Double, so you can pass a percentage directly:

// SwiftUI View modifiers
Text("Hello")
	.opacity(45%)
	.brightness(20%)
	.contrast(80%)
	.saturation(50%)
	.grayscale(100%)

// Color and ShapeStyle
Color.red.opacity(50%)

Rectangle()
	.fill(.red.opacity(50%))

// UIKit
UIColor.red.withAlphaComponent(50%)

// AppKit
NSColor.red.withAlphaComponent(50%)

Codable

The percentage value is encoded as a single value:

struct Foo: Codable {
	let alpha: Percentage
}

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 Swift Package Manager for this package even though you mainly use Carthage or CocoaPods.

Related

About

A percentage type for Swift

Topics

Resources

License

Code of conduct

Contributing

Stars

Watchers

Forks

Packages

No packages published

Contributors 5

Languages