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

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.)

Tags:

Pow

Swift3