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

1

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
}
Bobwhite answered 19/8, 2016 at 9:57 Comment(1)
Checkout apple code, may be this will help: github.com/apple/swift/blob/…Vassalize
O
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.

Orvah answered 19/8, 2016 at 10:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.