Search code examples
swiftoperator-precedence

odd numbers for operator precedence levels


just curious..is there a particular reason (historical or some sort) why Swift uses numbers from 160 to 90 to express default precedence levels of operators. Thanks


Solution

  • According to Apple's Operation Declaration documentation

    The precedence level can be any whole number (decimal integer) from 0 to 255

    Although the precedence level is a specific number, it is significant only relative to another operator.

    The simple answer is that 90 to 160 fall near the center of the 0 to 255 range.

    Now if you check all of Apple's binary expressions documentation, you will see that the default operators range from a precedence of 90 to a precedence of 160, as you stated in your question. This is a range of 70 and because precedence values are relative to each other, any starting/ending point for this range could be chosen.

    However, if they made the default values 0 to 70 or 185 to 255 then when a user created a custom operator, they could not give it a lower precedence than 0 or a higher precedence than 255, causing the operator to be equal to the precedence of Assignment operators or Exponentiative operators respectively.

    Therefore, the only logical thing to do is to start this range in the middle of the 0 to 255 range and rather than set the default values of the range to 93 - 163 (the closest to the actual center of the range as possible), they chose to choose the multiples of 10 (90 to 160) instead because in actuality the values do not matter except in relation to each other.