Swift Metaprogramming using Sourcery

Gabriel Marson
The Startup
Published in
3 min readMay 27, 2020

Every iOS developer already came up with the problem of boilerplate code once. Whether it is related to verbose architectures or protocol conformances such as Codable, Equatable or simply a init method. The problem exists and can be very time consuming.

This article is a simple tutorial of using Sourcery to generate boilerplate code for us.

So… What is Sourcery?

Sourcery is a code generator tool for Swift. It works by providing templates and creating protocols that tell Sourcery which template will be applied to each class/struct.

How does it work?

Before trying anything at all, install Sourcery through cocoapods or brew. After that, we need to specify the path where Sourcery will look for the templates, swift files, and where it will output the generated code. So, on your project target, create a new Run Script Phase and add a script like this:

sourcery --sources YourProject --templates YourProject/Templates --output YourProject/Autogenerated

There are many more options we can add, but for the sake of simplicity, let's keep it like that. You can also create a .yml file and specify more than one source and template paths. Check it out here.

Now, let's start with a simple example:

Equatable

Sourcery templates can be written in Stencil and swiftemplate. For this example, we will use an equatable template that already comes out of the box with sourcery. All we have to do is declare an AutoEquatable protocol, and every class or struct that conforms to it will get the equatable method implemented.

In my project, for example, I've declared the following protocols:

I’ve also declared three structs, simulating some components. As you can see, they conform to the protocols that I’ve mentioned above.

Once this is done, all you have to do is build your project and import the files generated by Sourcery(only for the first time).

Outcome

All the AutoEquatable classes/structs will have their own implementation declared in one file. Other files will be created as you declare more protocols and make them conform to your data.

This equatable template written in stencil:

Generates this code:

Custom init and custom decodable

Custom templates can also be written in swiftemplate. We can basically declare whatever we want to be generated. Here is the complete documentation.

In my example project, I’ve written a custom template to consider nullable variables and variables with default values as optionals in the init method. I’ve also used the provided codable template from Sourcery and created a custom decodable template. Check it out.

Where to go from here

  • Lecture from Krzysztof Zabłocki, in CocoaHeads
  • This tutorial is a very good way to start writting custom templates

--

--