Customizing Operators

Think about the custom Car class you’ve been working with in this book. It has a name, and you could easily add a price to it. What happens if you want to add two cars together? Swift does not know how to do this, so you need to tell it how. You might want to combine cars by name or by price, or you might want to do something else.

You can overload (that is, tell the operators to do something else) all the operators in Swift to do what you would expect for your custom types.

In the case of the custom Car class, you have to tell Swift how to add these two things together. Here is a full example of how you can define your own equality operator to see if two “ingredients” are equal:

enum DrinkType:UInt8 ...

Get Learning Swift™ Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.