Zero symbol in MeasurementFormatter

I'm having problems to declare/use a zero symbol for an unknown value when using

MeasurementFormatter
:


let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .decimal
numberFormatter.zeroSymbol = "?"

numberFormatter.string(from: 0.0) // '?'

let formatter = MeasurementFormatter()
formatter.unitOptions = .providedUnit
formatter.numberFormatter = numberFormatter

var distance = Measurement(value: 0, unit: .parsecs)
formatter.string(from: distance) // '0 pc' - expected: '? pc'

Trying different declarations of the value such as

Double.zero
doesn't change the output. Is this a conceptual thing or am I missing something here? Might this even be a bug?
Answered by Claude31 in 417875022

1. What you posted:

var distance = Measurement(value: 0, unit: .parsecs)

causes an error : Type 'Unit' has no member 'parsecs'


2. So do you mean (as in SO)

var distance = Measurement<UnitLength>(value: 0, unit: .parsecs)
formatter.string(from: distance) // '0 pc' - expected: '? pc'


3. On the other end, I tested:

var distance2 = Measurement(value: 0, unit: Unit(symbol: "pc"))
formatter.string(from: distance2)

And got

'? pc'


4. To avoid recreating a symbol from string:

var distance3 = Measurement(value: 0, unit: Unit(symbol: UnitLength.parsecs.symbol))
formatter.string(from: distance3)

And got

'? pc'


So, you cannot use 1. as proposed in your post.

But 4 works.

As discussed on other places, I'm not interested in string-replacements, rather than the WHY of this issue.

Accepted Answer

1. What you posted:

var distance = Measurement(value: 0, unit: .parsecs)

causes an error : Type 'Unit' has no member 'parsecs'


2. So do you mean (as in SO)

var distance = Measurement<UnitLength>(value: 0, unit: .parsecs)
formatter.string(from: distance) // '0 pc' - expected: '? pc'


3. On the other end, I tested:

var distance2 = Measurement(value: 0, unit: Unit(symbol: "pc"))
formatter.string(from: distance2)

And got

'? pc'


4. To avoid recreating a symbol from string:

var distance3 = Measurement(value: 0, unit: Unit(symbol: UnitLength.parsecs.symbol))
formatter.string(from: distance3)

And got

'? pc'


So, you cannot use 1. as proposed in your post.

But 4 works.

Thanks for the help! 4 is working fine but I would expect the same output from 2. Looks like a Radar candidate 🙂

You're right, it is a bit suprising that 2 does not work.


If you file a radar, could you post the reference here ?


have a good day.

Sure, here it is: FB7685455 and the link to open radar https://openradar.appspot.com/FB7685455.

Zero symbol in MeasurementFormatter
 
 
Q