12

I want to use ** to overload an exponent function. I works if I use something like "^" but the python way of doing is ** and I would like to use that with Swift. Any way to do that?

error: Operator implementation without matching operator declaration

@infix func ** (num: Double, power: Double) -> Double{
    return pow(num, power)
}

println(8.0**3.0) // Does not work
mfaani
  • 33,269
  • 19
  • 164
  • 293
Chéyo
  • 9,107
  • 9
  • 27
  • 44
  • Are you sure `^` works as intended? I've only got it to act as an addition: `println(1^2) == 3` – vol7ron Jun 10 '14 at 04:45
  • 1
    @vol7ron `^` is the Bitwise XOR Operator. `1^2` is just coincidentally equal to `1+2`. Please see [The Swift Programming Language](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language), Language Guide -> Advanced Operators -> Bitwise XOR Operator. – Lensflare Jun 26 '14 at 17:06
  • @Lensflare: I was speaking of Python, where `^` does not act as an exponent. I think I was wrong and misread the question, which suggests that he could overload `^` in Swift to act as a caret, but he wanted to use `**`, which was not working when trying to overload. – vol7ron Jun 26 '14 at 19:52
  • You need to use Jamie's answer to tell the compiler what function name you want to use. – Chéyo Jun 28 '14 at 15:30

2 Answers2

36

You need to declare the operator before defining the function, as follows:

In Swift 2:

import Darwin

infix operator ** {}

func ** (num: Double, power: Double) -> Double {
    return pow(num, power)
}

println(8.0 ** 3.0) // works

In Swift 3:

import Darwin

infix operator **

func ** (num: Double, power: Double) -> Double {
    return pow(num, power)
}

print(8.0 ** 3.0) // works
Jamie Forrest
  • 10,895
  • 6
  • 51
  • 68
4

To make sure that ** is executed before neighboring * or /, you'd better set a precedence.

infix operator ** { associativity left precedence 160 }

As http://nshipster.com/swift-operators/ shows, the exponentiative operators have 160 precedence, like << and >> bitwise shift operators do.

Ben Lu
  • 2,982
  • 4
  • 31
  • 54