Skip to content

Commit

Permalink
Accept more floatingpoint/integer types directly
Browse files Browse the repository at this point in the history
  • Loading branch information
sindresorhus committed Feb 21, 2020
1 parent 6ad1e1b commit 0513895
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 23 deletions.
29 changes: 6 additions & 23 deletions Sources/Percentage/Percentage.swift
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import Foundation
import CoreGraphics

/**
```
Expand Down Expand Up @@ -58,40 +57,28 @@ public struct Percentage: Hashable, Codable {
public var fraction: Double { rawValue / 100 }

/**
Create a `Percentage` from a `Double`.
```
Percentage(50.5)
//=> 50.5%
```
*/
public init(_ percentage: Double) {
self.rawValue = percentage
}

/**
Create a `Percentage` from a `CGFloat`.
Create a `Percentage` from a `BinaryFloatingPoint`, for example, `Double` or `CGFloat`.
```
let cgFloat: CGFloat = 50.5
Percentage(cgFloat)
//=> 50.5%
```
*/
public init(_ percentage: CGFloat) {
public init<T>(_ percentage: T) where T: BinaryFloatingPoint {
self.rawValue = Double(percentage)
}

/**
Create a `Percentage` from an `Int`.
Create a `Percentage` from a `BinaryInteger`, for example, `Int`.
```
let int = 50
Percentage(int)
//=> 50%
```
*/
public init(_ percentage: Int) {
public init<T>(_ percentage: T) where T: BinaryInteger {
self.rawValue = Double(percentage)
}

Expand Down Expand Up @@ -161,17 +148,13 @@ public postfix func % (value: Int) -> Percentage {
// swiftlint:enable static_operator

extension Percentage: ExpressibleByFloatLiteral {
public typealias FloatLiteralType = Double

public init(floatLiteral value: FloatLiteralType) {
public init(floatLiteral value: Double) {
self.rawValue = value
}
}

extension Percentage: ExpressibleByIntegerLiteral {
public typealias IntegerLiteralType = Double

public init(integerLiteral value: IntegerLiteralType) {
public init(integerLiteral value: Double) {
self.rawValue = value
}
}
Expand Down
6 changes: 6 additions & 0 deletions Tests/PercentageTests/PercentageTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,15 @@ final class PercentageTests: XCTestCase {
let int = 50
XCTAssertEqual(Percentage(int), 50%)

let int8: Int8 = 50
XCTAssertEqual(Percentage(int8), 50%)

let cgFloat: CGFloat = 50.5
XCTAssertEqual(Percentage(cgFloat), 50.5%)

let float: Float = 50.5
XCTAssertEqual(Percentage(float), 50.5%)

XCTAssertEqual(Percentage(fraction: 0.5), 50%)
XCTAssertEqual(50%.fraction, 0.5)

Expand Down

0 comments on commit 0513895

Please sign in to comment.