Why does the string NumberFormatter (from :) return an optional parameter?

Documentation Link

Why is the NumberFormatter function func string(from number: NSNumber) -> String? returns a String? , not String ? Are there certain inputs or states for NumberFormatter where this function can return zero? Sometimes I hear that these return types are less than ideal from Objective-C storage files, is this one of these cases?

+7
ios swift
source share
2 answers

There is an ancient answer (2002) to the Apple mailing list , which may partially answer your question:

The strange behavior is not NSNumber - NSNumber -stringValue seems to return the results you would expect. This is an NSNumberFormatter that returns unusual results.

The abstract problem is that NSNumberFormatter was originally written to handle monetary amounts for EOF, so it does not deal with unusual numbers (or general-purpose string formatting, for that matter).

A more specific problem is that when you ask for NSNumberFormatter for -stringForObjectValue: if the object is not NSDecimalNumber, it converts it to NSDecimalNumber using [NSDecimalNumber decimalNumberWithString: [objectValue stringValue]] which will not deal well with unusual prices to potentially other problems. Another problem, although I do not know what it is, is that I do not think that there is an NSDecimal (structural) representation of positive and negative infinity, as it exists for NaN.

I really do not understand that the answer is enough to say that for some reason it is returning, but I suspect that it is connected.

Here is the sample code in the original question, but none of them returns nil , it always gives a string.

+5
source share

Just for fun: here is an example (built, not real) where string(from:) really returns nil :

 let num = NSNumber(bytes: UnsafeRawPointer(bitPattern: 1)!, objCType: "v") print(num) // <> let fmt = NumberFormatter() fmt.numberStyle = .decimal let str = fmt.string(from: num) print(str as Any) // nil 

The reason is that this num does not represent a number: it is created using the NSValue (from which it inherits) the initializer init(bytes:objCType:) with a value representing void . ("v" is the encoding type for void , the value of the pointer does not matter.)

+5
source share

All Articles