Operator Overloading & Custom Operators in Swift

Operator Overloading
Every once in a while we will end up in situations where we would need the functionality of existing operators e.g. +, -, *, /, etc for our own classes or structures. Lets say you were creating a game called “Cube Collector”, wherein, you start with one small cube in a universe filled with cubes of all sizes. You have to look for new cubes and every time you find a cube, your cube size is increased by adding the newly found cube to existing cube.

Our cube definition could be

One way of achieving the desired result of adding cubes in Object Oriented world would be to add the addition method to our Cube Struct, which would look as follows

Lets say instead of using an “add” function, we wanted to use the existing “+” operator to add the cubes, as we find them in our game i.e.

Swift lets us achieve this by letting us over load the existing operators to our classes or structures. Overloading is a way of saying that the existing operator is now capable of adding the new data types. A function to add two cubes would be as follows

When overloading operators, we can not declare them within our own structs or classes, they have to be declared in global scope.

Custom Operators
Lets say there are treasure bags in the game and every time the player collects a treasure bag, his/her cube triples in size. To implement this functionality, lets create a custom operator. To create a custom operator, we need to pick a name, type, precedence and associativity for the operator. For description on type, precedence and associativity, please refer Apple’s Documentation. Since the cube will triple in size, lets name our custom operator “***” and define it as postfix. The input parameter is declared as inout since we are changing the existing cube.

As you can see, overloading existing operators and creating custom operators is quite easy in Swift. I would be cautious while overloading existing operators though, especially by making sure that I am not creating un expected behavior.