ios - swift 3 : Decimal to Int

标签 ios swift swift3 nsdecimalnumber

我尝试使用以下代码将 Decimal 转换为 Int:

Int(pow(Decimal(size), 2) - 1) 

但是我得到:

.swift:254:43: Cannot invoke initializer for type 'Int' with an argument list of type '(Decimal)' 

这里我知道 pow 正在返回一个 Decimal 但似乎 Int 没有构造函数和成员函数来将 Decimal 转换为 Int。< br/> 如何在 Swift 3 中将 Decimal 转换为 Int?

最佳答案

这是我更新的答案(感谢 Martin R 和 OP 的评论)。 OP 的问题只是在从结果中减去 1 后将 pow(x: Decimal,y: Int) -> Decimal 函数转换为 Int。我已经借助这个 SO post for NSDecimal 回答了这个问题和 Apple's documentation on Decimal .您必须将结果转换为 NSDecimalNumber,后者又可以转换为 Int:

let size = Decimal(2)
let test = pow(size, 2) - 1
let result = NSDecimalNumber(decimal: test)
print(Int(result)) // testing the cast to Int

关于ios - swift 3 : Decimal to Int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39731265/

相关文章:

ios - 在 ios 应用程序中使用 svg 或字体图标

swift - 输入 'Range<CGFloat> does not conform to protocol Sequence' (Swift 3)

ios - 在 Swift 中实现 SpriteKit tap 处理程序时的意外行为

ios - 在 TableView 中按月份倒序

ios - 指定 API 请求的参数

ios - 在 SpriteKit 游戏中制作 Facebook 帖子

ios - 如何获取 JSON 中的数据?

ios - 如何从连接到 Xcode 的设备中理解 ios 崩溃报告?

swift - 嵌套的 Swift 类不符合 Comparable

Swift Beacon 现在不能使用 Swift 3.0