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
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With