Repository Public MIT
1# ORIXUnits — public API23Swift 6.2 package, Foundation only, no networking, no UI, no number formatting. Platforms: iOS 26, macOS 15.4Everything is a `Sendable` value type; `UnitCatalog.standard` is safe to read from any isolation domain.56Contents: 331 units in 33 categories, plus two non-catalog families: financial rate conventions and currencies.78## Model910| Type | Role |11|---|---|12| `UnitCategoryID` | `enum … : String, CaseIterable` — `length, area, volume, mass, temperature, speed, acceleration, pressure, energy, power, force, time, angle, dataStorage, dataRate, fuelEconomy, frequency, torque, density, flowRate, electricCharge, voltage, electricCurrent, resistance, capacitance, inductance, dynamicViscosity, kinematicViscosity, illuminance, radioactivity, absorbedDose, doseEquivalent, typography` |13| `UnitCategory` | `id`, `name` (English), `symbolName` (SF Symbol), `dimension: UnitDimension`, `referenceUnitID`, `units`, `referenceUnit` |14| `UnitDefinition` | `id` (`"length.km"`, globally unique, stable), `categoryID`, `symbol`, `name`, `aliases`, `transform`, `precision`, `source`, `note`, `linearFactor` |15| `UnitTransform` | `.linear(ExactRational)` · `.affine(scale:offset:)` (temperature) · `.reciprocal(ExactRational)` (L/100 km) |16| `UnitPrecision` | `.exact` < `.irrational` (involves π, 38 digits) < `.approximate` (measured or conventional) |17| `UnitSource` | `.si, .nist, .iau, .iec, .codata, .icao, .statute, .convention` with `citation: String` |18| `ExactRational` | `numerator`/`denominator` as `Decimal`; `decimalValue`, `doubleValue`, `isEquivalent(to:)`, `reciprocal` |19| `UnitDimension` | exponents of m, kg, s, A, K, mol, cd + `angle`, `data`, `currency`; `*`, `/`, `power(_:)`, `description` (`kg·m²·s⁻²`) |20| `Conversion` | `value: Decimal`, `unitPrecision`, `isExactDecimal` |21| `UnitError` | `.incompatible(from:to:)`, `.unknownUnit`, `.undefinedAtZero(unit:)`, `.intervalNotSupported(unit:)`, `.notRepresentable`, `.rateOutOfDomain`, `.unknownCurrency`, `.invalidRate(code:)`, `.malformedECB` |2223The type is named `UnitDimension` (not `Dimension`) because Foundation already exports a `Dimension` class.24Unit names are English (BIPM spelling: metre, litre); localisation is left to the app, keyed on `UnitDefinition.id`.2526## Catalog2728```swift29let catalog = UnitCatalog.standard3031catalog.categories // [UnitCategory], in UnitCategoryID.allCases order32catalog.category(.length)?.units // picker content33catalog.unit(id: "length.km") // stable id → unit34catalog.units(matching: "pt") // [US pint, DTP point] — symbols repeat across categories35catalog.unit("um", in: .length) // µm36try catalog.resolve(from: "pt", to: "mL") // (US pint, millilitre): the pair picks the category37catalog.search("gallon") // ranked, case- and diacritic-insensitive, for a search field38catalog.search("gal", in: .volume)39```4041Lookup rules (`units(matching:)`, `unit(_:in:)`, `resolve(from:to:)`):42431. Symbols and aliases are **case-sensitive**: `mm` ≠ `Mm`, `mW` ≠ `MW`, `b` (bit) ≠ `B` (byte), `cal` ≠ `Cal` (kcal). A symbol typed in the wrong case resolves to nothing (`mPa` is never read as `MPa`).442. Names and spelled-out aliases are case-insensitive, plural `s` tolerated: `Inch`, `Kilometers`, `FEET`, `megapascal`.453. `µ` (U+00B5) and `μ` (U+03BC) are interchangeable, as are `Ω` (U+03A9) and the ohm sign (U+2126). ASCII aliases exist: `um`, `ug`, `uF`, `deg`, `degC`, `ohm`, `kohm`, `m2`, `m^2`, `sq ft`, `cc`, `kph`…464. Bare aliases with a regional default: `gal`, `qt`, `pt`, `cup`, `fl oz`, `tbsp`, `tsp`, `mpg` mean the **US** units; `ton` is the short ton; `year` is the Gregorian mean year; `therm` is the US therm. The display symbols are explicit (`gal (US)`, `gal (imp)`).4748## Converting4950```swift51let mi = catalog.unit(id: "length.mi")!, km = catalog.unit(id: "length.km")!5253try UnitConverter.convert(Decimal(1), from: mi, to: km) // 1.609344 exactly54try UnitConverter.convert(1.0, from: mi, to: km) // 1.609344 (Double)55try catalog.convert(Decimal(12), from: "in", to: "ft") // 156try catalog.convert(98.6, from: "°F", to: "°C") // 37.05758let c = try UnitConverter.conversion(Decimal(1), from: km, to: mi)59c.value // 0.62137119223733396961743418436331822159 (38 digits, half-even)60c.unitPrecision // .exact61c.isExactDecimal // false → show "≈"; true → show "="6263try UnitConverter.ratio(from: mi, to: km) // ExactRational? (nil for temperature / fuel consumption)64UnitConverter.precision(from: a, to: b) // weaker of the two units65UnitConverter.areCompatible(a, b) // same category66```6768- `Decimal` path: the whole conversion is an exact fraction of big integers, divided once; exact when the result terminates within 38 significant digits, otherwise rounded half-to-even to 38 digits.69- `Double` path: the double is read as its shortest round-tripping decimal, converted in `Decimal`, rounded once. `12.0 in → ft == 1.0`, `0.1 m → cm == 10.0`. Magnitudes outside 1e-60…1e60, infinities and NaN use plain binary arithmetic.70- Units of different categories throw `UnitError.incompatible`, even with the same dimension (J vs N·m, Gy vs Sv, Hz vs Bq).7172### Temperature: reading versus difference7374```swift75try catalog.convert(Decimal(10), from: "°C", to: "°F") // 50 (a reading)76try catalog.convert(Decimal(10), from: "°C", to: "°F", mode: .interval) // 18 (a difference)77```7879`mode: .interval` equals the normal conversion for linear units and throws `.intervalNotSupported` for L/100 km.8081### Fuel economy8283`L/100 km` and `gal/100 mi (US)` are reciprocal against `km/L`, `mpg (US)`, `mpg (imp)`, `mi/L`.84A zero on either side of a reciprocal conversion throws `UnitError.undefinedAtZero(unit:)`.8586### Precision note for the UI8788```swift89switch unit.precision {90case .exact: break // nothing to show91case .irrational: show(unit.note) // "… π held to 38 digits."92case .approximate: show(unit.note) // "Measured: … (CODATA 2022)."93}94unit.source.citation // "NIST Special Publication 811 (2008), Appendix B …"95```9697`note` is also set on exact units that need a label (US survey foot: deprecated; `mo`: mean Gregorian month; `px`: 96 dpi).9899## Financial rate conventions100101```swift102public enum RateConvention { case effectiveAnnual, nominal(periodsPerYear: Int), periodic(periodsPerYear: Int),103 continuous, effectiveDiscount, nominalDiscount(periodsPerYear: Int) }104// shorthands: .annual .semiannual .quarterly .monthly .weekly (52) .daily (365); RateConvention.common; .name105106try RateConverter.convertRate(0.06, from: .semiannual, to: .effectiveAnnual) // 0.0609107try RateConverter.convertRate(0.06, from: .semiannual, to: .monthly) // 0.05926346437436374108try RateConverter.convertRate(0.05, from: .semiannual, to: .periodic(periodsPerYear: 12)) // Canadian mortgage monthly rate109try RateConverter.effectiveAnnualRate(0.0499, in: .daily)110try RateConverter.accumulationFactor(0.06, in: .semiannual, years: 10) // 1.03^20111```112113Rates are fractions (0.06 = 6 %), per year except `.periodic` (per period). `Double` only. Out-of-domain inputs114(effective rate ≤ −100 %, discount ≥ 100 %, periods ≤ 0, NaN) throw `UnitError.rateOutOfDomain`.115116## Currency117118```swift119var rates = try CurrencyRates.parseECB(xml: data) // base EUR, source = ECB, timestamp = date at 16:00 Frankfurt time120try rates.convert(Decimal(100), from: "USD", to: "CAD") // cross rate through the base, Decimal, not rounded to cents121try rates.crossRate(from: "USD", to: "CAD")122rates.codes; rates.base; rates.source; rates.timestamp; rates.rate(for: "USD") // Rate(value:isManual:)123124rates.staleness(now: .now) // .fresh(age:) | .stale(age:) | .manual (threshold 24 h)125rates.staleness(now: .now, threshold: 4 * 86_400)126rates.staleness(from: "USD", to: "CAD", now: .now) // .manual only if one of the two legs is hand-entered127128try rates.setManualRate(Decimal(string: "1.50")!, for: "CAD") // units of CAD per unit of base129let own = try CurrencyRates.manual(base: "CAD", rates: ["USD": …], enteredAt: .now)130131let data = try JSONEncoder().encode(rates) // Codable; rates stored as decimal strings132133CurrencyInfo.common // 49 ISO 4217 currencies: code, name, minorUnits134CurrencyInfo.info(for: "JPY")?.minorUnits // 0135```136137- `rates[code]` = units of `code` per one unit of `base` (ECB quotation).138- There is no "live" state. A table is timestamped by its publisher, or manual. The app decides when to download; the timestamp is the publication time, never the download time. The ECB does not publish on weekends and TARGET holidays, so pick the threshold accordingly (a Monday-morning table is about 3 days old).139- `parseECB` accepts only the single-day document (`eurofxref-daily.xml`); the 90-day history is rejected.140- Rounding an amount to `minorUnits` is formatting and is left to the app.141142## Building143144```sh145swift build && swift test # from Packages/ORIXUnits146python3 Reference/generate_reference.py # regenerates Reference/*.tsv and Tests/ORIXUnitsTests/ReferenceData.swift147```148149Adding a unit: declare it in a `StandardCatalog+*.swift` file with its source, add the same id to150`Reference/generate_reference.py` derived independently, regenerate, run the tests (the coverage test fails if the151two lists differ).152