- Mastering macOS Programming
- Stuart Grimshaw
- 231字
- 2021-07-02 22:54:39
Implementing a custom operator
Having defined what it looks like, and how we use it, we now need to define what the new operator actually means. We could include an implementation in the main definition of the GridMovement class, but a convention is emerging to put such code in an extension. This makes sense when we consider that what we are actually doing is defining something that belongs not so much to the type itself, as to the code that uses it:
extension GridMovement
{
static prefix func -><- (movement: inoutGridMovement)
->GridMovement
{
return GridMovement(rows: movement.col, cols: movement.row)
}
}
Since this method mutates a variable (as opposed to returning a new one) we need to declare it as an inout parameter.
The inout keyword forces us to be explicit about the fact that we want to change a variable in place. Without that, a function assumes its arguments to be immutable. This is a good example of Swift's safety as default philosophy.
Try it out with something like the following code:
print(movementB)
-><-movementB
print(movementB)
In the console, we will see we have mutated the movementB variable.
We have chosen a deliberately provocative set of characters for the operator here. Given that any such operator could also be implemented as a function, any operators we create should be immediately readable.
There should be a strong rationale for creating an operator instead of a function.
There should be a strong rationale for creating an operator instead of a function.