Operator methods
Operator methods enable us to add implementations of standard Swift operators to classes and structures. This is also known as overloading operators. This is a very useful feature because it enables us to provide common functionality to our custom types using known operators. We'll take a look at how to do this, but first, let's create a custom type called MyPoint
:
struct MyPoint {
var x = 0
var y = 0
}
The MyPoint
structure defines a two-dimensional point on a graph. Now let's add three operator methods to this type. The operators that we will add are the addition operator (+
), the addition assignment operator (+=
), and the inverse operator (-
). The addition operator and the addition assignment operator are infix operators because there is a left and right operand (value) to the operation, while the inverse operator is a prefix operator because it is used before a single value. We also have postfix operators, which are used at the...