Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use ** for exponents using @infix func **( )?

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
like image 714
Chéyo Avatar asked Jun 06 '14 14:06

Chéyo


2 Answers

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
like image 145
Jamie Forrest Avatar answered Oct 22 '22 02:10

Jamie Forrest


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.

like image 35
Ben Lu Avatar answered Oct 22 '22 02:10

Ben Lu