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

2

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
Desk answered 6/6, 2014 at 14:53 Comment(4)
Are you sure ^ works as intended? I've only got it to act as an addition: println(1^2) == 3Cawnpore
@Cawnpore ^ is the Bitwise XOR Operator. 1^2 is just coincidentally equal to 1+2. Please see The Swift Programming Language, Language Guide -> Advanced Operators -> Bitwise XOR Operator.Sangsanger
@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.Cawnpore
You need to use Jamie's answer to tell the compiler what function name you want to use.Elwell
A
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
Adena answered 6/6, 2014 at 15:0 Comment(4)
As of beta 6 it must be written infix operator ** {}.Bigg
Thanks @Klaas, I updated the answer for Xcode 6 beta 6.Adena
Swift3: infix operator ** <--curly braces not neededMages
Thanks @GitSyncApp, I updated the answer with Swift 3 code as well.Adena
M
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.

Mathis answered 28/1, 2015 at 22:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.