Exponentiation operator in Swift
For anyone looking for a Swift 3 version of the **
infix operator:
precedencegroup ExponentiationPrecedence {
associativity: right
higherThan: MultiplicationPrecedence
}
infix operator ** : ExponentiationPrecedence
func ** (_ base: Double, _ exp: Double) -> Double {
return pow(base, exp)
}
func ** (_ base: Float, _ exp: Float) -> Float {
return pow(base, exp)
}
2.0 ** 3.0 ** 2.0 // 512
(2.0 ** 3.0) ** 2.0 // 64
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.
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