'Swift how to represent standard atmosphere pressure for unit conversion
I am making a unit converter app. When dealing with pressure, I found that there are already a few units predefined in Foundation:
UnitPressure.newtonsPerMetersSquared
UnitPressure.bars
UnitPressure.poundsForcePerSquareInch
But there's no standard atmosphere pressure. (Note that bar is not the same as standard atmosphere pressure, despite that they are close).
I am wondering how do i handle this case?
Solution 1:[1]
You can define your own units very easily:
extension UnitPressure {
static let standardAtmospheres = UnitPressure(
symbol: "atm",
converter: UnitConverterLinear(coefficient: 101325)
)
}
Measurement(value: 1, unit: UnitPressure.bars)
.converted(to: .standardAtmospheres) // 0.9869232667160128 atm
Measurement(value: 1, unit: UnitPressure.standardAtmospheres)
.converted(to: .bars) // 1.01325 bar
The symbol for standard atmospheres is "atm" and 1 atm = 101325 N/m^2 as suggested by WolframAlpha, hence the magic number used in the code.
Note that N/m^2 is the base unit of UnitPressure.
The
UnitPressureclass defines its base unit asnewtonsPerMetersSquaredand provides the following units, whichUnitConverterLinearconverters initialize with the given coefficients: [...]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Sweeper |
