Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

pow

swift3

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?

like image 514
zeeple Avatar asked Feb 20 '17 06:02

zeeple


2 Answers

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

like image 163
OOPer Avatar answered Nov 07 '22 06:11

OOPer


Int init() method with no parameter is deprecated for Decimal conversion and should be replaced with Int.init(truncating number: NSNumber) like this

let lootMod = Int(truncating: pow(Decimal(level), 2) * 2 as NSDecimalNumber)

Or

let lootMod = Int(truncating: NSDecimalNumber(decimal: pow(Decimal(level), 2) * 2))
like image 26
mulot Avatar answered Nov 07 '22 05:11

mulot