Skip to content

Operator Overloading

Operator overloading is one of the powerful features in Swift programming language. In an essence, it is basically using of -, +, ==, /, * operators on any type you’d like. Also, you can define your own operators and use them in your projects. How cool is that?
Let’s say you have a News project and you’re working with some articles:

Now, let’s say we need to check whether two articles are the same, but, logic is that they’re the same, only if id and title are the same.
Probably, we would do it in the old fashioned way, using an if statement.

The one would say that there’s nothing wrong with this code. It is working as expected. Yes, that is true. Let’s say that we add one more thing into this example – let’s say we add date property to our class and that our business logic is that if id, title and the date property is the same within two objects – then that means that they’re the same.
One thing you notice at once is that our if condition is not elegant at all. It’s huge and unsustainable. Add more to it – imagine that we have this code in couple of places. Terrible. We would definitely violate the DRY principle which stands for Don’t Repeat Yourself.

Let’s make a function:

Yes, function would do the trick. Now, we can use this function anywhere we want to. Also, if our business logic changes again – we would change it only in one place.
The code would like like this:

But, we already have a comparison operator in Swift, == operator. Wouldn’t it be cool that we use it instead? Sure.

Let’s look at our final code:

Now we have an elegant solution.
At some point, we all used those heavy if statements. Now that you see the power of Swift’s operator overloading,
I hope you’ve enjoyed this tutorial. Have a nice day!
Published iniOS

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: