Swift elevation operator

I do not see the exponential operator defined in basic arithmetic operations in the Swift help system.

In fact, there is no predefined integer or float operator of an exponential expression in the language?

+42
swift exponentiation
Jun 05 '14 at 16:46
source share
6 answers

There is no operator, but you can use the pow function as follows:

return pow(num, power) 

If you want, you can also call the pow operator function as follows:

 infix operator ** { associativity left precedence 170 } func ** (num: Double, power: Double) -> Double{ return pow(num, power) } 2.0**2.0 //4.0 
+53
Jun 05 '14 at 16:57
source share

If you possibly raise 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 

Note that the value of "power" is 1 less than you think.

Note that this is faster than pow(2.0, 8.0) and avoids the use of doubles.

+12
Feb 22 '15 at 23:16
source share

For anyone looking for a version of the Operational Index ** Swift 3:

 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 
+9
Jan 11 '17 at 2:19
source share

I did it like this:

 operator infix ** { associativity left precedence 200 } func ** (base: Double, power: Double) -> Double { return exp(log(base) * power) } 
+6
Jun 24 '14 at 20:22
source share

There is not one, but you have the pow function.

+2
Jun 05 '14 at 16:54 on
source share

Like most C-family languages, they are not.

+1
Jun 05 '14 at 16:52
source share



All Articles