百分比

一个 Swift 的百分比类型

使百分比更具可读性和类型安全性,例如,对于当前接受分数 Double 的 API。

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

安装

将以下内容添加到 Package.swift

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

或者在 Xcode 中添加包。

用法

请查看 源代码 以获取文档。

import Percentage

10% + 5.5%
//=> 15.5%

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

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

50% * 50%
//=> 25%

30% > 25%
//=> true

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

Percentage(50)
//=> 50%

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

50%.fraction
//=> 0.5

10%.rawValue
//=> 10

110%.clampedZeroToHundred
//=> 100%

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

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

该类型符合 HashableCodableRawRepresentableComparableExpressibleByFloatLiteralExpressibleByIntegerLiteralNumeric,并支持所有算术运算符。

Codable

百分比值被编码为单个值

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}"

常见问题解答

你能支持 Carthage 和 CocoaPods 吗?

不能,但是即使你主要使用 Carthage 或 CocoaPods,你仍然可以使用 Swift Package Manager 来管理这个包。

相关