Why does NumberFormatter's string(from:) return an optional?

前端 未结 3 1153
后悔当初
后悔当初 2021-01-04 05:43

Documentation link

Why does the NumberFormatter function func string(from number: NSNumber) -> String? return a String? rat

3条回答
  •  心在旅途
    2021-01-04 06:09

    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.)

提交回复
热议问题