我尝试使用以下代码将 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/