Sorry, but I have been waiting for months to make this pun. So today, we are going to talk about Operator overloading in Swift. This tool is very useful, but quite dangerous as well. The “With great power comes great responsibility,” quote is very appropriate for operator overloading. It can make your code a lot more concise, making even a function call seem like a 3-hour long lecture. But with that, you can also make the code nigh-unreadable to anybody that is new to your code.
Be very careful with this tool, and use it where it make sense, such as how “adding” two Swift Strings together makes a new string with one string first, then the other afterwards. You can make the addition operator print to the screen, make a network request, play music, or whatever else you could write a function for, but doing any of those would be a terrible idea in production code. You should do only what is necessary for the operator and nothing else. If you need different things like those, make an appropriately named function that makes it obvious that it will make a network request.
Whenever you think of whether to use operator overloading, you have to ponder whether it helps your code anymore than a simple function call. The function call may be longer, but it is a whole lot more expressive as to what it does (if named appropriately). If it looks like you are adding, subtracting, checking equality, or whatever else the built-in operators do though, and you do it enough in your code, Swift’s operator overloading may be the right tool for the job.
[Read more…]