Exponentiation operator in Swift

mcgregor94086 picture mcgregor94086 · Jun 5, 2014 · Viewed 63.6k times · Source

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?

Answer

Connor picture Connor · Jun 5, 2014

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