A percentage type for Swift

Overview

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

Comments
  • Build error:

    Build error: "Use of undeclared type 'CGFloat'"

    Just tried pulling this into a new Xcode 11.1 project using the GUI SPM flow, and got this build error.

    Adding

    import CoreGraphics
    

    at the top of Percent.swift fixed it for me. Happy to submit a PR if you want it!

    opened by armcknight 1
  • Codable Implementation

    Codable Implementation

    Hey Sindre, this is a cool library! If I'm reading the source code correctly, suppose I had the following struct:

    struct SomeObject: Codable {
        let alpha: Percent
    }
    

    That object would be encoded as below (and require the below JSON to decode):

    {
        alpha: {
            rawValue: 10
        }
    }
    

    it may be a nice enhancement to override the default Encodable/Decodable implementations to parse that struct as:

    {
        alpha: 0.1
    }
    

    I feel this is more likely what you'd get from an API. Up to you whether you want to keep the implementation as is, entirely change it to the above, or maybe provide some static variable to allow users to choose which Codable representation they want.

    opened by nevillco 1
  • Store it internally as `Decimal`

    Store it internally as `Decimal`

    opened by sindresorhus 1
  • Make percentage of given value generic

    Make percentage of given value generic

    Prior to this change, calculating such percentage from values of types different than Double would require type casting boilerplate. Now it is possible to find percentage of any BinaryInteger or BinaryFloatingPoint, with result always matching the original input type. Having mixed input and output is also supported, meaning it is possible to obtain the percentage of BinaryInteger as BinaryFloatingPoint (although not vice-versa; using an explicit type casting seems more reasonable in such cases).

    opened by irisdelaluna 0
  • Add static `.random(in:)` method

    Add static `.random(in:)` method

    I am using this in an app and I thougt it might be useful to have it in the standard package.

    Similar to Double.random(in:) (which it uses internally)

    I would have added tests but I am not sure how to test something that is random by design 🤔

    opened by alexbinary 0
  • Conform it to `Numeric`?

    Conform it to `Numeric`?

    Not sure whether there are any downsides with doing that, but would be nice if Percentage could be used with generic numeric methods.

    https://developer.apple.com/documentation/swift/numeric

    opened by sindresorhus 0
  • Add overloads for Swift and Cocoa APIs?

    Add overloads for Swift and Cocoa APIs?

    Would be nice to be able to use this with Swift/Cocoa APIs that accept a fraction Double.

    For example:

    • https://developer.apple.com/documentation/uikit/uicolor/1621922-withalphacomponent
    • https://developer.apple.com/documentation/appkit/nscolor/1526906-withalphacomponent
    • https://developer.apple.com/documentation/swiftui/color/3049763-opacity
    • https://developer.apple.com/documentation/swiftui/hstack/3269261-opacity
    • https://developer.apple.com/documentation/swiftui/hstack/3269155-brightness
    • https://developer.apple.com/documentation/swiftui/hstack/3269164-contrast
    • https://developer.apple.com/documentation/swiftui/hstack/3269293-saturation
    • https://developer.apple.com/documentation/swiftui/hstack/3269207-grayscale

    Does this make sense?

    opened by sindresorhus 0
  • Add more useful properties

    Add more useful properties

    Some ideas:

    • .clampedZeroToHundred which clamps the percentage to 0...100.
    • Percent.from(100, of: 200) //=> 50%
    • Find the original value before a percent increase. E.g. If a value is 120 after a 40% increase, what is the original value before the increase?
    • Find the original value before a percent decrease. E.g. If a value is 106 after a 12% decrease, what is the original value before the decrease?
    • "x IS y% OF". E.g. 67 is 90% of what?

    What else?

    help wanted 
    opened by sindresorhus 0
Releases(v1.2.0)
  • v1.2.0(Sep 27, 2022)

  • v1.1.0(Dec 27, 2020)

    • Make percentage of given value generic (#11) https://github.com/sindresorhus/Percentage/commit/66243465ff0d2746701edb01c3244e2128941b39

    https://github.com/sindresorhus/Percentage/compare/v1.0.0...v1.1.0

    Source code(tar.gz)
    Source code(zip)
  • v1.0.0(Jul 6, 2020)

    Breaking

    • Rename package from Percent to Percentage 76480b7

    Improvements

    • Conform to ExpressibleByFloatLiteral, ExpressibleByIntegerLiteral, and Numeric 6ad1e1b
    • Accept more floatingpoint/integer types directly 0513895
    • Add static .random(in:) method (#9) ac33f86

    Fixes

    • Fix multiplication and division for percentages 50a5144

    https://github.com/sindresorhus/Percentage/compare/v0.2.0...v1.0.0

    Source code(tar.gz)
    Source code(zip)
  • v0.2.0(Nov 13, 2019)

  • v0.1.1(Oct 3, 2019)

  • v0.1.0(Oct 1, 2019)

Owner
Sindre Sorhus
Full-Time Open-Sourcerer. Focuses on Swift & JavaScript. Makes macOS apps, CLI tools, npm packages. Likes unicorns.
Sindre Sorhus
A type-safe, protocol-based, pure Swift database offering effortless persistence of any object

There are many libraries out there that aims to help developers easily create and use SQLite databases. Unfortunately developers still have to get bogged down in simple tasks such as writing table definitions and SQL queries. SwiftyDB automatically handles everything you don't want to spend your time doing.

Øyvind Grimnes 489 Sep 9, 2022
Swift APIs for SQLite: Type-safe down to the schema. Very, very, fast. Dependency free.

Lighter Lighter is a set of technologies applying code generation to access SQLite3 databases from Swift, e.g. in iOS applications or on the server. L

Lighter.swift 330 Dec 26, 2022
TypedDefaults is a utility library to type-safely use NSUserDefaults.

TypedDefaults TypedDefaults is a utility library to type-safely use NSUserDefaults. Motivation The talk Keep Calm and Type Erase On by Gwendolyn Westo

Kazunobu Tasaka 110 Feb 6, 2022
A protocol-centric, type and queue safe key-value workflow.

Light-weight, strict protocol-first styled PropertyKit helps you to easily and safely handle guaranteed values, keys or types on various situations of

gitmerge 12 Feb 26, 2021
A Generic CoreData Manager to accept any type of objects. Fastest way for adding a Database to your project.

QuickDB FileManager + CoreData ❗️ Save and Retrieve any thing in JUST ONE line of code ❗️ Fast usage dataBase to avoid struggling with dataBase comple

Behrad Kazemi 17 Sep 24, 2022
A fast, pure swift MongoDB driver based on Swift NIO built for Server Side Swift

A fast, pure swift MongoDB driver based on Swift NIO built for Server Side Swift. It features a great API and a battle-tested core. Supporting both MongoDB in server and embedded environments.

null 646 Dec 10, 2022
🧡 SQLiteOrm-Swift is an ORM library for SQLite3 built with Swift 5

?? Easy to use SQLite ORM library written with Swift

Yevgeniy Zakharov 25 Oct 6, 2022
ObjectBox Swift - persisting your Swift objects superfast and simple

ObjectBox Swift ObjectBox is a superfast, light-weight object persistence framework. This Swift API seamlessly persists objects on-device for iOS and

ObjectBox 380 Dec 19, 2022
Shows the issue with swift using an ObjC class which has a property from a swift package.

SwiftObjCSwiftTest Shows the issue with swift using an ObjC class which has a property from a swift package. The Swift class (created as @objc derived

Scott Little 0 Nov 8, 2021
Ios-App-ication-Swift - A simple iOS application made in Xcode using Swift

?? iPhone Calculator A simple iOS application made in Xcode using Swift. This ap

Kushal Shingote 1 Feb 2, 2022
Save-the-dot-project-swift - Save the dot project with swift

Save the Dot Apple introduced UIViewPropertyAnimator for iOS 10. We can use this

Kushal Shingote 2 Feb 8, 2022
The Swift Package Index is the place to find Swift packages!

The Swift Package Index helps you make better decisions about the dependencies you use in your apps. The Swift Package Index is a search engine for pa

Swift Package Index 389 Dec 22, 2022
A stand-alone Swift wrapper around the mongo-c client library, enabling access to MongoDB servers.

This package is deprecated in favour of the official Mongo Swift Driver. We advise users to switch to that pack

PerfectlySoft Inc. 54 Jul 9, 2022
Elegant library to manage the interactions between view and model in Swift

An assistant to manage the interactions between view and model ModelAssistant is a mediator between the view and model. This framework is tailored to

Seyed Samad Gholamzadeh 28 Jan 29, 2022
CRUD is an object-relational mapping (ORM) system for Swift 4+.

CRUD is an object-relational mapping (ORM) system for Swift 4+. CRUD takes Swift 4 Codable types and maps them to SQL database tables. CRUD can create tables based on Codable types and perform inserts and updates of objects in those tables. CRUD can also perform selects and joins of tables, all in a type-safe manner.

PerfectlySoft Inc. 61 Nov 18, 2022
CoreXLSX is a Excel spreadsheet (XLSX) format parser written in pure Swift

CoreXLSX Excel spreadsheet (XLSX) format parser written in pure Swift CoreXLSX is a library focused on representing the low-level structure of the XML

null 684 Dec 21, 2022
Solutions to LeetCode by Swift

LeetCode by Swift LeetCode Online Judge is a website containing many algorithm questions. Most of them are real interview questions of Google, Faceboo

Soap 4.5k Jan 5, 2023
Super lightweight DB written in Swift.

Use of value types is recommended and we define standard values, simple structured data, application state and etc. as struct or enum. Pencil makes us store these values more easily.

Naruki Chigira 88 Oct 22, 2022
YapDB is a collection/key/value store with a plugin architecture. It's built atop sqlite, for Swift & objective-c developers.

YapDatabase is a collection/key/value store and so much more. It's built atop sqlite, for Swift & Objective-C developers, targeting macOS, iOS, tvOS &

Yap Studios 3.3k Dec 29, 2022