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

I want to use ** to overload the exponent function. I work if I use something like "^", but the python method is **, and I would like to use this with swift. Any way to do this?

Error: operator implementation with declaration of conformance operator

@infix func ** (num: Double, power: Double) -> Double{ return pow(num, power) } println(8.0**3.0) // Does not work 
+6
source share
2 answers

You need to declare an operator before defining a 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 
+26
source

To make sure ** runs to the next * or /, you better set priority.

 infix operator ** { associativity left precedence 160 } 

As shown by http://nshipster.com/swift-operators/ , exponential operators have priority 160, for example, <<and → bitwise shift operators.

+4
source

Source: https://habr.com/ru/post/970457/


All Articles