Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift3 : how to handle precedencegroup now operator should be declare with a body?

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
}
like image 396
Stéphane de Luca Avatar asked Aug 19 '16 09:08

Stéphane de Luca


1 Answers

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.

like image 98
Hamish Avatar answered Nov 20 '22 05:11

Hamish