Custom operators

We are not limited to coding implementations of the operators we know already. If we need to implement an operator for functionality for which +, % and so on make no sense (or are already in use), we can define our own, using any of a set of characters allowed by Swift.

The following is a list of characters that may make up custom operators:

 / = - + ! ? * % <>& | ^ ~ 

Operators may also start with a. character.

There are also some other Unicode characters that are allowed, but are not valid as first characters. See Apple's documentation if you need to go beyond the set listed previously.

To write a custom operator, we need to complete two steps:

  • Define the operator itself
  • Implement the behavior of the operator
Remember that we can do this by extending existing types, including those provided by Swift, such as  Int and String.

In the next section, we will write an operator that swaps the rows and columns dimensions of our GridMovement struct.