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?
CodePudding user response:
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
UnitPressure
class defines its base unit asnewtonsPerMetersSquared
and provides the following units, whichUnitConverterLinear
converters initialize with the given coefficients: [...]