Skip to content

Commit

Permalink
feature: Adds a unitless percent unit
Browse files Browse the repository at this point in the history
  • Loading branch information
Jairon Terrero committed Sep 9, 2024
1 parent 4e14254 commit de8256c
Show file tree
Hide file tree
Showing 3 changed files with 71 additions and 0 deletions.
9 changes: 9 additions & 0 deletions Sources/Units/Unit/DefaultUnits.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1055,4 +1055,13 @@ enum DefaultUnits {
dimension: [.Length: 3],
coefficient: 0.00025
)

// MARK: Unitless

static let percent = try! DefinedUnit(
name: "percent",
symbol: "%",
dimension: [:],
coefficient: 0.01
)
}
4 changes: 4 additions & 0 deletions Sources/Units/Unit/Unit+DefaultUnits.swift
Original file line number Diff line number Diff line change
Expand Up @@ -245,4 +245,8 @@ public extension Unit {
static let imperialPint = Unit(definedBy: DefaultUnits.imperialPint)
static let imperialGallon = Unit(definedBy: DefaultUnits.imperialGallon)
static let metricCup = Unit(definedBy: DefaultUnits.metricCup)

// MARK: Unitless

static let percent = Unit(definedBy: DefaultUnits.percent)
}
58 changes: 58 additions & 0 deletions Tests/UnitsTests/MeasurementTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,64 @@ final class MeasurementTests: XCTestCase {
)
}

func testPercent() throws {
XCTAssertEqual(
1.measured(in: .percent),
1.measured(in: .percent)
)

XCTAssertNotEqual(
100.measured(in: .percent),
1.measured(in: .none)
)

try {
let percent1 = 5.measured(in: .percent)
let percent2 = 5.measured(in: .percent)
XCTAssertEqual(
try percent1 + percent2,
10.measured(in: .percent),
accuracy: accuracy
)
}()

try {
let percent1 = 5.measured(in: .percent)
let value2 = 5.measured(in: .none)
XCTAssertThrowsError(try percent1 + value2)
}()

XCTAssertTrue(
2.measured(in: .percent).isDimensionallyEquivalent(
to: 2.measured(in: .percent)
)
)

XCTAssertTrue(
2.measured(in: .percent).isDimensionallyEquivalent(
to: 2.measured(in: .none)
)
)

XCTAssertEqual(
try 1.measured(in: .percent).convert(to: .none),
0.01.measured(in: .none),
accuracy: accuracy
)

XCTAssertEqual(
try 1.measured(in: .none).convert(to: .percent),
100.measured(in: .percent),
accuracy: accuracy
)

_ = {
let measurement = 1.measured(in: .percent) / 2.measured(in: .second)
XCTAssertEqual(measurement.unit, Unit.percent / Unit.second)
XCTAssertEqual(measurement.value, 0.5, accuracy: accuracy)
}()
}

func testComplexArithmetic() throws {
XCTAssertEqual(
try 1.measured(in: .mile / .mile) * 1.measured(in: .mile) - 1.measured(in: .mile),
Expand Down

0 comments on commit de8256c

Please sign in to comment.