In this Swift tutorial, you’ll learn how to create custom operators, overload existing operators and set operator precedence. By Owen L Brown.

Leave a rating/review
Save for later
Share

## Contents

20 mins

### Dot Product Precedence

Your new dot-product doesn’t really fit into any of these categories. It has to be less than addition (as you realized before), but does it really fit into `CastingPrecedence` or `RangeFormationPrecedence`?

Replace your original declaration of the `•` operator with the following:

```precedencegroup DotProductPrecedence {
associativity: left
}

infix operator •: DotProductPrecedence
```

Here, you create a new precedence group and name it `DotProductPrecedence`. You place it lower than `AdditionPrecedence` because you want addition to take precedence. You also make it left-associative because you want it evaluated from left-to-right as you do in addition and multiplication. Then you assign this new precedence group to your `•` operator.

Note: In addition to `lowerThan`, you can also specify `higherThan` in your `DotProductPrecedence`. This becomes important if you have multiple custom precedence groups in a single project.

Your old line of code now runs and returns as expected:

```vectorA • vectorB + vectorA // 29
```

Congratulations — you've mastered custom operators!

## Where to Go From Here?

At this point, you know how to bend Swift operators to your needs. In this tutorial, you focused on using operators in a mathematical context. In practice, you’ll find many more ways to use operators.

A great demonstration of custom operator usage can be seen in the ReactiveSwift framework. One example is `<~` for binding, an important function in reactive programming. Here is an example of this operator in use:

```let (signal, _) = Signal<Int, Never>.pipe()
let property = MutableProperty(0)
property.producer.startWithValues {
}

property <~ signal
```

Cartography is another framework that heavily uses operator overloading. This AutoLayout tool overloads the equality and comparison operators to make `NSLayoutConstraint` creation simpler:

```constrain(view1, view2) { view1, view2 in
view1.width   == (view1.superview!.width - 50) * 0.5
view2.width   == view1.width - 50
view1.height  == 40
view2.height  == view1.height
view1.centerX == view1.superview!.centerX
view2.centerX == view1.centerX

view1.top >= view1.superview!.top + 20
view2.top == view1.bottom + 20
}
```

Additionally, you can always reference the official custom operator documentation from Apple.

Armed with these new sources of inspiration, you can go out into the world and make your code simpler with operator overloading. Just be careful not to go too crazy with custom operators! :]

If you have any questions or comments on this tutorial, please join the discussion below!

Owen L Brown

## Contributors

Owen L Brown

Author

Evan Dekhayser

Author

Bas Broek

Tech Editor

Illustrator

Final Pass Editor