Operator Overloading By Adding Two Objects To Themselves.

-How much is it 2 plus 2?
-Easy, of course, it is 4.
-OK, how much is to a glass of apple juice plus a glass of orange juice?
-Ummh, two glasses?
-Not exactly…

Adding numbers is a theoretically trivial task to do. 2 + 2 = 4, 64 + 1024 = 1088 and so on. It becomes more complex when we want to add two things which have more parameters than the only number…

Let’s say we have a glass of apple juice (100 milliliters) and a glass of orange juice (100 milliliters). Yet, how to add them? We need to find a way we will add one to another. Our juice has three parameters like name, volume, and price.

Apple juice:

-name: Apple

-volume: 100

-price: 5

Orage juice:

-name: Orange

-volume: 100

-price: 7

In this case, the result after addition should be one juice with name contains both names, prices added up and volumes added up.

Operator Overloading gif
Adding two juices in our case

Operator Overloading in code:

We have Juice class (it can be struck as well):

class Juice {
    var name: String = “”
    var volume: Int = 0
    var price: Int = 0

    init() {
    }

    init(name: String, volume: Int, price: Int) {
        self.name = name
        self.volume = volume
        self.price = price
    }
}

Somewhere else in the code are two objects of Juice class:

let appleJuice = Juice(name: “Apple”, volume: 100, price: 5)
let orangeJuice = Juice(name: “Orange”, volume: 100, price: 7)

What does happen when we try to add them?

let mixJuice = appleJuice + orangeJuice

We will receive:

Binary operator ‘+’ cannot be applied to two ‘Juice’ operands

Binary operator '+' cannot be applied
Binary operator ‘+’ cannot be applied

The compiler doesn’t know what to do. Why? We didn’t tell how it should be done.

Let’s back to our Juice class and add one static method inside Juice class or as an extension.

extension Juice {
    static func + (lhs: Juice, rhs: Juice) -> Juice {
         let juice = Juice()
         juice.name = lhs.name + ” and “ + rhs.name
         juice.price = lhs.price + rhs.price
         juice.volume = lhs.volume + rhs.volume
         return juice
     }
}

Now out code complies and we have our mixed juice.

print(“Name: \(mixJuice.name)”)
print(“Volume: \(mixJuice.volume)”)
print(“Price: \(mixJuice.price)”)

Output:

Name: Apple and Orange
Volume: 130
Price: 30