ORIXUnits — public API
Swift 6.2 package, Foundation only, no networking, no UI, no number formatting. Platforms: iOS 26, macOS 15.
Everything is a Sendable value type; UnitCatalog.standard is safe to read from any isolation domain.
Contents: 331 units in 33 categories, plus two non-catalog families: financial rate conventions and currencies.
Model
| Type | Role |
|---|---|
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 |
UnitCategory |
id, name (English), symbolName (SF Symbol), dimension: UnitDimension, referenceUnitID, units, referenceUnit |
UnitDefinition |
id ("length.km", globally unique, stable), categoryID, symbol, name, aliases, transform, precision, source, note, linearFactor |
UnitTransform |
.linear(ExactRational) · .affine(scale:offset:) (temperature) · .reciprocal(ExactRational) (L/100 km) |
UnitPrecision |
.exact < .irrational (involves π, 38 digits) < .approximate (measured or conventional) |
UnitSource |
.si, .nist, .iau, .iec, .codata, .icao, .statute, .convention with citation: String |
ExactRational |
numerator/denominator as Decimal; decimalValue, doubleValue, isEquivalent(to:), reciprocal |
UnitDimension |
exponents of m, kg, s, A, K, mol, cd + angle, data, currency; *, /, power(_:), description (kg·m²·s⁻²) |
Conversion |
value: Decimal, unitPrecision, isExactDecimal |
UnitError |
.incompatible(from:to:), .unknownUnit, .undefinedAtZero(unit:), .intervalNotSupported(unit:), .notRepresentable, .rateOutOfDomain, .unknownCurrency, .invalidRate(code:), .malformedECB |
The type is named UnitDimension (not Dimension) because Foundation already exports a Dimension class.
Unit names are English (BIPM spelling: metre, litre); localisation is left to the app, keyed on UnitDefinition.id.
Catalog
let catalog = UnitCatalog.standard
catalog.categories // [UnitCategory], in UnitCategoryID.allCases order
catalog.category(.length)?.units // picker content
catalog.unit(id: "length.km") // stable id → unit
catalog.units(matching: "pt") // [US pint, DTP point] — symbols repeat across categories
catalog.unit("um", in: .length) // µm
try catalog.resolve(from: "pt", to: "mL") // (US pint, millilitre): the pair picks the category
catalog.search("gallon") // ranked, case- and diacritic-insensitive, for a search field
catalog.search("gal", in: .volume)Lookup rules (units(matching:), unit(_:in:), resolve(from:to:)):
- 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 (mPais never read asMPa). - Names and spelled-out aliases are case-insensitive, plural
stolerated:Inch,Kilometers,FEET,megapascal. µ(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…- Bare aliases with a regional default:
gal,qt,pt,cup,fl oz,tbsp,tsp,mpgmean the US units;tonis the short ton;yearis the Gregorian mean year;thermis the US therm. The display symbols are explicit (gal (US),gal (imp)).
Converting
let mi = catalog.unit(id: "length.mi")!, km = catalog.unit(id: "length.km")!
try UnitConverter.convert(Decimal(1), from: mi, to: km) // 1.609344 exactly
try UnitConverter.convert(1.0, from: mi, to: km) // 1.609344 (Double)
try catalog.convert(Decimal(12), from: "in", to: "ft") // 1
try catalog.convert(98.6, from: "°F", to: "°C") // 37.0
let c = try UnitConverter.conversion(Decimal(1), from: km, to: mi)
c.value // 0.62137119223733396961743418436331822159 (38 digits, half-even)
c.unitPrecision // .exact
c.isExactDecimal // false → show "≈"; true → show "="
try UnitConverter.ratio(from: mi, to: km) // ExactRational? (nil for temperature / fuel consumption)
UnitConverter.precision(from: a, to: b) // weaker of the two units
UnitConverter.areCompatible(a, b) // same categoryDecimalpath: 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.Doublepath: the double is read as its shortest round-tripping decimal, converted inDecimal, 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.- Units of different categories throw
UnitError.incompatible, even with the same dimension (J vs N·m, Gy vs Sv, Hz vs Bq).
Temperature: reading versus difference
try catalog.convert(Decimal(10), from: "°C", to: "°F") // 50 (a reading)
try catalog.convert(Decimal(10), from: "°C", to: "°F", mode: .interval) // 18 (a difference)mode: .interval equals the normal conversion for linear units and throws .intervalNotSupported for L/100 km.
Fuel economy
L/100 km and gal/100 mi (US) are reciprocal against km/L, mpg (US), mpg (imp), mi/L.
A zero on either side of a reciprocal conversion throws UnitError.undefinedAtZero(unit:).
Precision note for the UI
switch unit.precision {
case .exact: break // nothing to show
case .irrational: show(unit.note) // "… π held to 38 digits."
case .approximate: show(unit.note) // "Measured: … (CODATA 2022)."
}
unit.source.citation // "NIST Special Publication 811 (2008), Appendix B …"note is also set on exact units that need a label (US survey foot: deprecated; mo: mean Gregorian month; px: 96 dpi).
Financial rate conventions
public enum RateConvention { case effectiveAnnual, nominal(periodsPerYear: Int), periodic(periodsPerYear: Int),
continuous, effectiveDiscount, nominalDiscount(periodsPerYear: Int) }
// shorthands: .annual .semiannual .quarterly .monthly .weekly (52) .daily (365); RateConvention.common; .name
try RateConverter.convertRate(0.06, from: .semiannual, to: .effectiveAnnual) // 0.0609
try RateConverter.convertRate(0.06, from: .semiannual, to: .monthly) // 0.05926346437436374
try RateConverter.convertRate(0.05, from: .semiannual, to: .periodic(periodsPerYear: 12)) // Canadian mortgage monthly rate
try RateConverter.effectiveAnnualRate(0.0499, in: .daily)
try RateConverter.accumulationFactor(0.06, in: .semiannual, years: 10) // 1.03^20Rates are fractions (0.06 = 6 %), per year except .periodic (per period). Double only. Out-of-domain inputs
(effective rate ≤ −100 %, discount ≥ 100 %, periods ≤ 0, NaN) throw UnitError.rateOutOfDomain.
Currency
var rates = try CurrencyRates.parseECB(xml: data) // base EUR, source = ECB, timestamp = date at 16:00 Frankfurt time
try rates.convert(Decimal(100), from: "USD", to: "CAD") // cross rate through the base, Decimal, not rounded to cents
try rates.crossRate(from: "USD", to: "CAD")
rates.codes; rates.base; rates.source; rates.timestamp; rates.rate(for: "USD") // Rate(value:isManual:)
rates.staleness(now: .now) // .fresh(age:) | .stale(age:) | .manual (threshold 24 h)
rates.staleness(now: .now, threshold: 4 * 86_400)
rates.staleness(from: "USD", to: "CAD", now: .now) // .manual only if one of the two legs is hand-entered
try rates.setManualRate(Decimal(string: "1.50")!, for: "CAD") // units of CAD per unit of base
let own = try CurrencyRates.manual(base: "CAD", rates: ["USD": …], enteredAt: .now)
let data = try JSONEncoder().encode(rates) // Codable; rates stored as decimal strings
CurrencyInfo.common // 49 ISO 4217 currencies: code, name, minorUnits
CurrencyInfo.info(for: "JPY")?.minorUnits // 0rates[code]= units ofcodeper one unit ofbase(ECB quotation).- 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).
parseECBaccepts only the single-day document (eurofxref-daily.xml); the 90-day history is rejected.- Rounding an amount to
minorUnitsis formatting and is left to the app.
Building
swift build && swift test # from Packages/ORIXUnits
python3 Reference/generate_reference.py # regenerates Reference/*.tsv and Tests/ORIXUnitsTests/ReferenceData.swiftAdding a unit: declare it in a StandardCatalog+*.swift file with its source, add the same id to
Reference/generate_reference.py derived independently, regenerate, run the tests (the coverage test fails if the
two lists differ).