ios - 为什么 NSDecimalNumber.notANumber.intValue 返回 9?

标签 ios swift foundation nsdecimalnumber

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

enter image description here

最佳答案

就像 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?,它将包含它的值,或者如果它不能由 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/

相关文章:

objective-c - 如何在解析中调用变量?

objective-c - 如何在 NSDictionary 中交换键和值?

ios - 使用 swift : [SimpleRunner. 运行 setTime:] 时出现核心数据错误:无法识别的选择器发送到实例

ios - 动态更改静态单元格上的节标题文本

ios - 使用从 Firebase 获取的数据填充 tableView

ios - swift 的字符串类型是否符合集合协议(protocol)?

swift - 扩展 Foundation 类以符合 Swift 协议(protocol)

swift - "data.map(Result.success)"是如何工作并返回一种类型的 Result<Data, Error> 的?

ios - 在没有团队帐户的情况下在 Xcode 中开发同一个应用程序

ios - 将函数 void 移动到 bool Swift