Combining answers into an overloaded set of functions (and using "**" instead of "^^", as some other languages use, is clearer for me):
// http://stackoverflow.com/questions/24196689/how-to-get-the-power-of-some-integer-in-swift-language // Put this at file level anywhere in your project infix operator ** { associativity left precedence 160 } func ** (radix: Double, power: Double) -> Double { return pow(radix, power) } func ** (radix: Int, power: Int ) -> Double { return pow(Double(radix), Double(power)) } func ** (radix: Float, power: Float ) -> Double { return pow(Double(radix), Double(power)) }
When using Float, you may lose accuracy. If you use numeric literals and a combination of integers and non-integers, you will get Double by default. I personally like the ability to use a mathematical expression instead of a function like pow (a, b) for stylistic / readability, but that's just me.
Any statements that cause a pow () error will also call these functions to cause an error, so the burden of error checking is still in the code using the power function. KISS, IMHO.
Using the native pow () function allows, for example, to take square roots (2 ** 0.5) or inverse (2 ** -3 = 1/8). Due to the ability to use inverse or fractional measures, I wrote all my code to return the double type of pow () function by default, which should return maximum accuracy (if I remember the documentation correctly). If necessary, this can be reset using an Int or Float type or something else, possibly with a loss of precision.
2 ** -3 = 0.125 2 ** 0.5 = 1.4142135623731 2 ** 3 = 8
ECJB Oct 17 '15 at 3:34 2015-10-17 03:34
source share