我try 用以下代码将十进制转换为整数:
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
我try 用以下代码将十进制转换为整数:
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
这是我最新的答案(感谢Martin R和OP的 comments ).OP的问题是从结果中减go 1后,将pow(x: Decimal,y: Int) -> Decimal
函数转换为整数.在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