Using Swift's Measurement() type convert String into UnitType

110 Views Asked by At

I am internationalizing my app to accept and return measurements in any system. Because of this I won't be able to use a hard coded UnitType when creating a Measurement(value: value, unit: unit) (user chooses unit type from a picker). I'm storing the user entered values into Core Date by separately storing the value as a Double and the UnitType as a String. for example:

person.height = 190.0
person.heightUnit = "UnitLength.centimeters"

If I were to hard code the UnitType as UnitLength.centimeters, as below:

let personHeight = 190.0

let height = Measurement(value: personHeight, unit: UnitLength.centimeters)

Text("Height = \(height.formatted(.measurement(width: .abbreviated, usage: .personHeight).locale(Locale(identifier: "en-US"))))")

It returns the expected "Height = 6 ft, 2.8 in"

If I then try to construct a UnitType from the value in person.heightUnit as in the following:

let personHeight = 190.0
let personHeightUnit = "UnitLength.centimeters"

let unit = UnitLength(symbol: personHeightUnit)
let height = Measurement(value: personHeight, unit: unit)
Text("Height = \(height.formatted(.measurement(width: .abbreviated, usage: .personHeight).locale(Locale(identifier: "en-US"))))")

This returns "Height = 0 in"

How do I convert the String "UnitLength.centimeters" as stored in CoreData into a type Unit that works with Measurement?

0

There are 0 best solutions below