We’ve now compared struct property access to enum associated value access and seen how structs are much more ergonomic by default, but we’ve also seen that we can recover these ergonomics on enums by defining our own computed properties per case. Unfortunately it comes at the cost of manual intervention: where the compiler gives us struct properties and key paths for free, we’re responsible for defining enum properties by hand, so it’s easy for us to forget to do so, and we can easily end up in a situation where some enum cases have properties defined while others don’t.
In order to embrace the idea of enum properties and benefit from their ergonomics universally without having to remember to take the time to define them by hand, we can turn to code generation. The Swift community has a bunch of tools that help here. The standard library team uses gyb
, which stands for “generate your boilerplate”. It uses Python to interpolate templates and generate a bunch of standard library boilerplate. Another popular community tool is Sourcery. Today we’re going to use a relatively new tool from Apple called SwiftSyntax
, which is a Swift language wrapper around libSyntax
, a library for parsing and inspecting Swift source code.