integerdoubleswiftpow

How to get the Power of some Integer in Swift language?


I'm learning swift recently, but I have a basic problem that can't find an answer

I want to get something like

var a:Int = 3
var b:Int = 3 
println( pow(a,b) ) // 27

but the pow function can work with double number only, it doesn't work with integer, and I can't even cast the int to double by something like Double(a) or a.double()...

Why it doesn't supply the power of integer? it will definitely return an integer without ambiguity ! and Why I can't cast a integer to a double? it just change 3 to 3.0 (or 3.00000... whatever)

if I got two integer and I want to do the power operation, how can I do it smoothly?

Thanks!


Solution

  • If you like, you could declare an infix operator to do it.

    // Put this at file level anywhere in your project
    infix operator ^^ { associativity left precedence 160 }
    func ^^ (radix: Int, power: Int) -> Int {
        return Int(pow(Double(radix), Double(power)))
    }
    
    // ...
    // Then you can do this...
    let i = 2 ^^ 3
    // ... or
    println("2³ = \(2 ^^ 3)") // Prints 2³ = 8
    

    I used two carets so you can still use the XOR operator.

    Update for Swift 3

    In Swift 3 the "magic number" precedence is replaced by precedencegroups:

    precedencegroup PowerPrecedence { higherThan: MultiplicationPrecedence }
    infix operator ^^ : PowerPrecedence
    func ^^ (radix: Int, power: Int) -> Int {
        return Int(pow(Double(radix), Double(power)))
    }
    
    // ...
    // Then you can do this...
    let i2 = 2 ^^ 3
    // ... or
    print("2³ = \(2 ^^ 3)") // Prints 2³ = 8