Need help with Percentage?
Click the “chat” button below for chat support from the developer who created it, or find similar developers for support.

About the developer

sindresorhus
240 Stars 18 Forks MIT License 23 Commits 4 Opened issues

Description

A percentage type for Swift

Services available

!
?

Need anything else?

Contributors list

# 216
exec
test-fr...
nextjs
messeng...
20 commits
# 190,256
Swift
codable
iphone
swift-p...
1 commit
# 157,681
Swift
swift-p...
macOS
Xcode
1 commit

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: "1.1.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%

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

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

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

The type conforms to

Hashable
,
Codable
,
RawRepresentable
,
Comparable
,
ExpressibleByFloatLiteral
,
ExpressibleByIntegerLiteral
,
Numeric
, and supports all the arithmetic operators.

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

We use cookies. If you continue to browse the site, you agree to the use of cookies. For more information on our use of cookies please see our Privacy Policy.