Sergio Bost
Sergio Bost

Reputation: 3219

My custom operator needs a precedence group?

So I have a custom operator that works fine when comparing one pair of numbers but fails when I try to compare more than one pair. The code snippet below can be thrown right into a playground to replicate the error.

infix operator ≈

 func ≈ (lhs: Int, rhs: Int) -> Bool {
      lhs < rhs + 80 && lhs > rhs - 80
 }

 let results = 100 ≈ 75 && 89 ≈ 78 //<-- `Adjacent operators are in unordered precedence groups 'DefaultPrecedence' and 'LogicalConjunctionPrecedence'`

I read the docs on it but did not receive much understanding on how to fix this error.

Upvotes: 0

Views: 367

Answers (1)

Andy Ray
Andy Ray

Reputation: 32066

You either need to group your operands:

let results = (100 ≈ 75) && (89 ≈ 78)

Or define your new operator precedence:

precedencegroup CongruentPrecedence {
    lowerThan: MultiplicationPrecedence
    higherThan: AdditionPrecedence
    associativity: left
}

infix operator ≈:CongruentPrecedence

Upvotes: 3

Related Questions