我在我的代码中发现了一个由 NSDecimalNumber.notANumber.intValue
返回 9 引起的错误,而我期望 NaN
(如 floatValue
或 doubleValue
返回)。有人知道为什么吗?
最佳答案
就像 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 值,所以你会得到这个错误的结果。
相反,您可以使用 Int
的 Failable Initialiser init(exactly:)
将您的 NSDecimalNumber 转换为一个 Int?
,它将包含它的值,或者如果它不能由 Int
表示,则为 nil
。
let strangeNumber = NSDecimalNumber.notANumber // nan
let integerRepresentation = Int(exactly: strangeNumber) // nil
关于ios - 为什么 NSDecimalNumber.notANumber.intValue 返回 9?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54074353/