Custom Operators

suggest change

Swift supports the creation of custom operators. New operators are declared at a global level using the operator keyword.

The operator’s structure is defined by three parts: operand placement, precedence, and associativity.

  1. The prefix, infix and postfix modifiers are used to start an custom operator declaration. The prefix and postfix modifiers declare whether the operator must be before or after, respectively, the value on which it acts. Such operators are urnary, like 8 and 3++ **, since they can only act on one target. The infix declares a binary operator, which acts on the two values it is between, such as 2+3.
  2. Operators with higher precedence are calculated first. The default operator precedence is just higher than ?: (a value of 100 in Swift 2.x). The precedence of standard Swift operators can be found here.
  3. Associativity defines the order of operations between operators of the same precedence. Left associative operators are calculated from left to right (reading order, like most operators), while right associative operators calculate from right to left.

Starting from Swift 3.0, one would define the precedence and associativity in a precedence group instead of the operator itself, so that multiple operators can easily share the same precedence without referring to the cryptic numbers. The list of standard precedence groups is shown below.

Operators return values based on the calculation code. This code acts as a normal function, with parameters specifying the type of input and the return keyword specifying the calculated value that the operator returns.

Here is the definition of a simple exponential operator, since standard Swift does not have an exponential operator.

import Foundation    

infix operator ** { associativity left precedence 170 }

func ** (num: Double, power: Double) -> Double{
    return pow(num, power)
}

The infix says that the ** operator works in between two values, such as 9**2. Because the function has left associativity, 3**3**2 is calculated as (3**3)**2. The precedence of 170 is higher than all standard Swift operations, meaning that 3+2**4 calculates to 19, despite the left associativity of **.

import Foundation 

infix operator **: BitwiseShiftPrecedence

func ** (num: Double, power: Double) -> Double {
    return pow(num, power)
}

Instead of specifying the precedence and associativity explicitly, on Swift 3.0 we could use the built-in precedence group BitwiseShiftPrecedence that gives the correct values (same as <<, >>).

**: The increment and decrement are deprecated and will be removed in Swift 3.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents