We all hate to copy and paste boring and repetitive boilerplate code. It happens in every project, iOS in particular. It appears in many places throughout our code base and it’s an indirect violation of the DRY principle. We all know that it’s a bad sign.

It’s an issue that doesn’t usually get enough attention. It involves getting out of our comfort zone, as generating code can be hard.

Fortunately, we have a solution to start automating boilerplate code in our Swift projects. I stumbled upon it while searching for a solution for our project at the office. It took me quite a while to get things going so I decided to layout a simple example to start with.

Let’s take a look at this example:

Now, we want to compare our Car struct in various places in our code. So we extend it to conform the Equatable protocol

While some might say: well it’s one method… 4 lines of code and a bit of copy paste. It’s really not that bad.

Think about that:

The Swift compiler won’t fail if you missed a variable while comparing.

Every time you add new properties you have to remember to revisit this method manually .

. You could potentially have multiple boilerplate functions spreading across multiple amounts of files (Hashable, Description, Tests, Enum cases etc’).

Dealing with these cases will become a hassle, repetitive and most of all, dangerous. This is where all of the sneaky runtime bugs can easily appear.