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?
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?
If you happen to be raising 2 to some power, you can use the bitwise left shift operator:
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.If you're specifically interested in the exponentiation operator for
Int
type, I don't think that existing answers would work particularly well for large numbers due to the way how floating point numbers are represented in memory. When converting toFloat
orDouble
fromInt
and then back (which is required bypow
,powf
andpowl
functions inDarwin
module) you may lose precision. Here's a precise version forInt
:Note that this version isn't particularly memory efficient and is optimized for source code size.
Another version that won't create an intermediate array: