Documentation link
Why does the NumberFormatter
function func string(from number: NSNumber) -> String?
return a String?
rat
Just for fun: Here is a (constructed, not real-world) example where
string(from:)
actually 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 its inherits) initializer
init(bytes:objCType:) with a value representing void
. ("v" is the type encoding for void
,
the pointer value is irrelevant.)