Custom operators
Custom operators enable us to declare and implement our own operators outside of the standard operators provided by the Swift language. New operators must be declared globally using the operator
keyword. They must also be defined with the infix
, prefix
, or postfix
keywords. Once an operator is defined globally, we are then able to add it to our types using the operator methods as shown in the previous section. Let's take a look at this by adding two new operators: •
, which we will use to multiply two points together, and ••
, which will be used to square a value. We will add these operators to the MyPoint
type that we created in the last section.
The •
symbol can be typed by holding down the option key and pressing the number 8 on a computer running macOS.
The first thing we need to do is to declare the operators globally. This can be done with the following code:
infix operator •
prefix operator •...