请注意: The pow()
函数返回一个decimal
value.
并且,要转换这个decimal
值对Int
值,人们可以简单地想到以下两个之一:
-
Int(pow(x, y))
... [IE。直接的Decimal
to Int
转换]
-
Int(Double(pow(x, y)))
... [IE。Decimal
to Double
to Int
一次转换]
然而,这两者都会产生相同的结果Ambiguous use of 'pow'
错误(下面的屏幕截图)。
然而有趣的是,如果我们用两行代码打破第二个选项,那就是:
a) Decimal to Double
, 进而
b) Double to Int
...它就像一个魅力!
这是您想要的确切功能,无需直接使用Int
值(根据需要):
func getGigaSeconds(from seconds: Int) -> Int {
let gigaPower: Double = pow(10, 9)
let gigaSeconds = seconds * Int(gigaPower)
return gigaSeconds
}
EDIT:
The Apple Developer documentation shows that the y
parameter of the pow()
function is an Int
, while both x
and the return-type
are Decimal
.
结论:
以下变体有效:
// 1) `y` is a `Double`
let gigaSeconds = Int(pow(10, Double(9)))
// 2) `x` is a `Double`
let gigaSeconds = Int(pow(Double(10), 9))
// 3) Both, `x` and `y` are `Double`
let gigaSeconds = Int(pow(Double(10), Double(9)))
// 4) Both, `x` and `y` are `Int` but the end result is a `Double` (which is then converted to an `Int`
let gigaPower: Double = pow(10, 9)
let gigaSeconds = seconds * Int(gigaPower)