From 0513895234bdf42f451e52211a552e47800326af Mon Sep 17 00:00:00 2001 From: Sindre Sorhus Date: Fri, 21 Feb 2020 20:15:39 +0700 Subject: [PATCH] Accept more floatingpoint/integer types directly #1 --- Sources/Percentage/Percentage.swift | 29 +++++---------------- Tests/PercentageTests/PercentageTests.swift | 6 +++++ 2 files changed, 12 insertions(+), 23 deletions(-) diff --git a/Sources/Percentage/Percentage.swift b/Sources/Percentage/Percentage.swift index ff435e6..769b076 100644 --- a/Sources/Percentage/Percentage.swift +++ b/Sources/Percentage/Percentage.swift @@ -1,5 +1,4 @@ import Foundation -import CoreGraphics /** ``` @@ -58,19 +57,7 @@ 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 @@ -78,12 +65,12 @@ public struct Percentage: Hashable, Codable { //=> 50.5% ``` */ - public init(_ percentage: CGFloat) { + public init(_ 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 @@ -91,7 +78,7 @@ public struct Percentage: Hashable, Codable { //=> 50% ``` */ - public init(_ percentage: Int) { + public init(_ percentage: T) where T: BinaryInteger { self.rawValue = Double(percentage) } @@ -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 } } diff --git a/Tests/PercentageTests/PercentageTests.swift b/Tests/PercentageTests/PercentageTests.swift index 057ea77..fc24aaf 100644 --- a/Tests/PercentageTests/PercentageTests.swift +++ b/Tests/PercentageTests/PercentageTests.swift @@ -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)