Search code examples
swift3pow

How to use pow() in Swift 3 and get an Int


I have the following code:

let lootBase = Int(pow((Decimal(level + 1)), 3) * 2)
let lootMod = Int(pow(Decimal(level), 2) * 2)
value = Int(arc4random_uniform(UInt32(lootBase)) + lootMod)

I need value to be an Int. The error I get when I try to surround the pow calculation for Int() is:

Cannot invoke initializer for type int with an argument list of type Decimal

How do I use the pow function with Int in Swift 3?


Solution

  • Int does not have an initializer taking Decimal, so you cannot convert Decimal to Int directly with an initializer syntax like Int(...).

    You can use pow(Decimal, Int) like this:

    let lootBase = Int(pow((Decimal(level + 1)), 3) * 2 as NSDecimalNumber)
    let lootMod = Int(pow(Decimal(level), 2) * 2 as NSDecimalNumber)
    
    let value = Int(arc4random_uniform(UInt32(lootBase))) + lootMod
    

    Or else, you can use pow(Double, Double) like this:

    let lootBase = Int(pow((Double(level + 1)), 3) * 2)
    let lootMod = Int(pow(Double(level), 2) * 2)
    
    let value = Int(arc4random_uniform(UInt32(lootBase))) + lootMod
    

    But, if you only calculate an integer value's power to 2 or 3, both pow(Decimal, Int) and pow(Double, Double) are far from efficient.

    You can declared a simple functions like squared or cubed like this:

    func squared(_ val: Int) -> Int {return val * val}
    func cubed(_ val: Int) -> Int {return val * val * val}
    

    and use them instead of pow(..., 2) or pow(..., 3):

    let lootBase = cubed(level + 1) * 2
    let lootMod = squared(level) * 2
    
    let value = Int(arc4random_uniform(UInt32(lootBase))) + lootMod
    

    (Assuming level is an Int.)