为什么 NSDecimalNumber.notANumber.intValue return 9?

Why does NSDecimalNumber.notANumber.intValue return 9?

我在我的代码中发现了一个由 NSDecimalNumber.notANumber.intValue returning 9 引起的错误,而我希望 NaN(如 floatValuedoubleValue return)。有人知道为什么吗?

就像 Joakim Danielson 提到的和在 Apple Developer Documentation

中提到的

... Because numeric types have different storage capabilities, attempting to initialize with a value of one type and access the value of another type may produce an erroneous result ...

并且由于 Swift 的 Int 结构不能表示 NaN 值,所以您会得到这个错误的结果。

相反,您可以使用 IntFailable Initialiser init(exactly:) 将您的 NSDecimalNumber 转换为一个 Int?,它将包含它的值或者如果它不可表示则为 nil通过 Int.

let strangeNumber = NSDecimalNumber.notANumber          // nan
let integerRepresentation = Int(exactly: strangeNumber) // nil