Swift Syntax Enum Properties

Episode #53 • Apr 8, 2019 • Subscriber-Only

We’ve seen how “enum properties” help close the gap between the ergonomics of accessing data on structs and enums, but defining them by hand requires a lot of boilerplate. This week we join forces with Apple’s Swift Syntax library to generate this boilerplate automatically!

Previous episode
Swift Syntax Enum Properties
Next episode
Locked

Unlock This Episode

Our Free plan includes 1 subscriber-only episode of your choice, plus weekly updates from our newsletter.

Sign in with GitHub

Introduction

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.

Swift Package Manager


Get started with our free plan

Our free plan includes 1 subscriber-only episode of your choice, access to 64 free episodes with transcripts and code samples, and weekly updates from our newsletter.

View plans and pricing