25

Former Swift 3 code for operator was:

infix operator × {associativity left precedence 150}

But now, as per Xcode 8 beta 6, this generate the following warning:

"operator should not be declared with body"

What's the right way to use precedencegroup predicate as no doc exists right now?

I have tried this, but does not work:

infix operator × : times
precedencegroup times {
     associativity: left 
     precedence: 150
}
Hamish
  • 69,859
  • 16
  • 167
  • 245
Stéphane de Luca
  • 10,239
  • 7
  • 45
  • 74
  • Checkout apple code, may be this will help: https://github.com/apple/swift/blob/3d005f3ad90f041325e7a28fd9d0544324ac24d6/test/Parse/operator_decl.swift – Ankit Thakur Aug 19 '16 at 10:36

1 Answers1

60

As per SE-0077, the precedence of an operator is no longer determined by a magic number – instead you now use the higherThan and (if the group resides in another module) lowerThan precedencegroup relationships in order to define precedence relative to other groups.

For example (from the evolution proposal):

// module Swift
precedencegroup Additive { higherThan: Range }
precedencegroup Multiplicative { higherThan: Additive }

// module A
precedencegroup Equivalence {
  higherThan: Comparative
  lowerThan: Additive  // possible, because Additive lies in another module
}
infix operator ~ : Equivalence

1 + 2 ~ 3    // same as (1 + 2) ~ 3, because Additive > Equivalence
1 * 2 ~ 3    // same as (1 * 2) ~ 3, because Multiplicative > Additive > Equivalence
1 < 2 ~ 3    // same as 1 < (2 ~ 3), because Equivalence > Comparative
1 += 2 ~ 3   // same as 1 += (2 ~ 3), because Equivalence > Comparative > Assignment
1 ... 2 ~ 3  // error, because Range and Equivalence are unrelated

Although in your case, as it appears that your operator is used for multiplication, you could simply use the standard library's MultiplicationPrecedence group, which is used for the * operator:

infix operator × : MultiplicationPrecedence

It is defined as:

precedencegroup MultiplicationPrecedence {
  associativity: left
  higherThan: AdditionPrecedence
}

For a full list of standard library precedence groups, as well as more info about this change, see the evolution proposal.

Hamish
  • 69,859
  • 16
  • 167
  • 245