1

How can I make the exponentiation operator ** in Swift behave the same as in other programming languages.

The question Exponentiation operator in Swift has the following answer which has the highest number of up votes,

infix operator ** { associativity left precedence 170 }

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

However, y = -x**2,

  • is interpreted as (-x)**2 = 4.0 (Swift)
  • usually it should be interpreted as -(x**2) = -4.0 (Expected!)
Community
  • 1
  • 1
Daniel Farrell
  • 9,316
  • 8
  • 39
  • 62

1 Answers1

1

I believe your problem is:

Unary operators in Swift always take precedence over binary operators.

Here's the source: https://medium.com/swift-programming/facets-of-swift-part-5-custom-operators-1080bc78ccc

Therefore, the expression is always evaluated as (-x)**2 instead of -(x**2), since - is a unary operator and ** is a binary operator.

ABakerSmith
  • 22,759
  • 9
  • 68
  • 78