Episode #261

Sourcery

12 minutes
Published on March 23, 2017

This video is only available to subscribers. Get access to this video and 572 others.

Writing boilerplate code can get tedious and boring. It can also lead to code duplication, which means it becomes a liability to keep in sync. Sourcery is a code generation tool that can help leverage your existing types and reflect on them in order to generate useful bits of code. In this episode Sam Soffes shows us how to install and use Sourcery, how to integrate it with Xcode’s build system, and how to create a simple Sorcery template to automatically count the number of items in a Swift enum and add it as an option.

This week's guest author is Sam Soffes.

Episode Links

Installing Sourcery

The easiest way to install it is with homebrew...

$ brew install sourcery

Running it

The command-line interface is structured like this:

sourcery <source folder> <template folder> <output folder>

So you'd likely run it like this:

sourcery Sources Templates Generated

Autocases example

One interesting example is to have Sourcery automatically generate a list of all possible values in an enum, which can be handy for a number of reasons.

Given an enum like this:


// we have to give this a "marker" protocol so
// we know which enum types to work on...
protocol AutoCases { }

enum World: AutoCases {
  case earth
  case mars
  case jupiter
}

And a template like this:

{% for enum in types.implementing.AutoCases|enum %}
extension {{ enum.name }} {
  static var count: Int { return {{ enum.cases.count }} }
  {% if not enum.hasAssociatedValues %}
  static var allCases: [{{ enum.name }}] {
    return [
      {% for case in enum.cases %}.{{ case.name }}{% if not forloop.last %},{% endif %}
      {% endfor %}]
  }
  {% endif %}
}
{% endfor %}

The output looks like this:

extension World {
  static var count: Int { return 3 }

  static var allCases: [World] {
    return [
      .earth,
      .mars,
      .jupiter
      ]
  }

}

This episode uses Sourcery 0.59, Swift 3.