Precedence and associativity

Your shiny new custom operator seems to work just fine, but if you use it in a complex expression Swift won’t know what to do with it:

2 2 * 3 2 // Does not compile!

In order to understand this expression, Swift needs the following information about your operator:

  • Precedence: Should the multiplication be done before or after the exponentiation?
  • Associativity: Should the consecutive exponentiations be done left to right, or right to left?

Without this information, the only way to get Swift to understand your code is to add parentheses:

2 (2 * (3 2))

These parentheses are telling Swift that the exponentations should be done before the multiplication, and from right to left. If this is always the case, you can define this behavior using a precedence group.

Change your operator definition to the following:

precedencegroup ExponentiationPrecedence { associativity: right

higherThan: MultiplicationPrecedence

}

infix operator **: ExponentiationPrecedence

Here, you're creating a precedence group for your exponentiation operator, telling Swift it is right-associative and has higher precedence than multiplication.

Swift will now understand your expression, even without parentheses:

2 2 * 3 2

That’s it for custom operators. Time for some fun with subscripts, arrays and dictionaries!

results matching ""

    No results matching ""