measurementFormatter.string not returning spurious information

The demo was really interesting and enjoyable Neils.

The second Text view in the CaffeineAmountView returns "0 lb" in the widget instead of the expected "56.23 mg" as set in the static constant in the extension. Is this just a bug in the beta or is something else going on?

Code Block language
     Text(measurementFormatter.string(from: data.caffeineAmount))


Ok, this issue was resolve by as follows. First a getCaffeineAmount method is created in the CaffeineAmountView:

Code Block Swift
    func getCaffeineAmount(_ mass: Measurement<UnitMass>) -> String {
        let measurementFormatter = MeasurementFormatter()
measurementFormatter.unitOptions = .providedUnit
        return measurementFormatter.string(from: mass)
    }


Then from the main VStack in the same struct, instead of the Text view,

Code Block Swift
Text(measurementFormatter.string(from: data.caffeineAmount))


the following method call is made from a Text view:

Code Block Swift
Text(getCaffeineAmount(data.caffeineAmount))


Any suggestions are welcome, regarding a different approach as I am certain there are many.

Hi,

MeasurementFormatter is a powerful API, which means it sometimes requires a bit of configuration to get exactly the behavior you'd like. In this case, you can use the .providedUnit measurement option for the formatter, and pass it a Measurement in .milligrams:

Code Block
let formatter = MeasurementFormatter()
formatter.unitOptions = [.providedUnit]
let string = formatter.string(for: Measurement(value: 60, unit: UnitMass.milligrams))!
print(string) // Prints "60 mg"


More documentation on MeasurementFormatter: https://developer.apple.com/documentation/foundation/measurementformatter
Thank you very much for your reply.
measurementFormatter.string not returning spurious information
 
 
Q