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%)
SwiftPM:
.package(url: "https://github.com/sindresorhus/Percent", from: "0.1.1")
Or just copy-paste it.
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.
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}"
No, but you can still use SwiftPM for this package even though you mainly use Carthage or CocoaPods.
- Defaults - Swifty and modern UserDefaults
- Preferences - Add a preferences window to your macOS app
- LaunchAtLogin - Add "Launch at Login" functionality to your macOS app
- DockProgress - Show progress in your app's Dock icon
- CircularProgress - Circular progress indicator for your macOS app
- More…