Exponentiation operator in Swift

I don't see an exponentiation operator defined in the base arithmetic operators in the Swift language reference.

Is there really no predefined integer or float exponentiation operator in the language?


There isn't an operator but you can use the pow function like this:

return pow(num, power)

If you want to, you could also make an operator call the pow function like this:

infix operator ** { associativity left precedence 170 }

func ** (num: Double, power: Double) -> Double{
    return pow(num, power)
}

2.0**2.0 //4.0

If you happen to be raising 2 to some power, you can use the bitwise left shift operator:

let x = 2 << 0    // 2
let y = 2 << 1    // 4
let z = 2 << 7    // 256

Notice that the 'power' value is 1 less than you might think.

Note that this is faster than pow(2.0, 8.0) and lets you avoid having to use doubles.