Skip to content

3.Sourcery AutoCases

AliSoftware edited this page Sep 21, 2017 · 10 revisions

Classroom Walkthrough (Part 3)

First practical usage: AutoCases

Step 3.1

Autocases.stencil is a template provided by Sourcery to generate a list of all cases of enums

  • Open sourcery-0.8.0/Templates/AutoCases.stencil with your favorite text editor to take a look at the template

💡 You can see that the template will only loop on types implementing the AutoCases protocol. This is what we call a "phantom protocol", that is a protocol which won't really have any practical usage in your code for the compiler, but is used to annotate the enums we're interested in that code generation.

This allows us to avoid generating the static let allCases property for all enums, and only doing opt-in.

  • Copy the AutoCases.stencil template from sourcery-0.8.0/Templates to CodeGenDemo/CodeGen/Templates
$ cp sourcery-0.8.0/Templates/AutoCases.stencil CodeGenDemo/CodeGen/Templates
  • Create a new folder CodeGenDemo/Sources/Protocols, add it to your Xcode project
  • Add the following SourceryProtocols.swift file in that folder to contain the declaration of that phantom protocol:
protocol AutoCases {}

💡 The file name SourceryProtocols.swift doesn't matter (it has no hidden special meaning), but we'll later add more phantom protocols in there, so let's use some generic name for it 😉

  • Annotate the enum PhoneModel (in Sources/Model/PhoneModel.swift) to conform to that new phantom protocol:
enum PhoneModel: String, AutoCases {
  

Step 3.2

  • Start a Build (Command-B) so that Sourcery generates the code using the AutoCases.stencil template
  • Add the generated file AutoCases.generated.swift to the CodeGen/Generated group of your Xcode project
  • Start another Build (Command-B) to realize that the compiler will complain about redeclaration of allCases.
  • You can now remove all that extension PhoneModel declaring static let allCases from your own code, it's now generated and maintained by Sourcery!

Step 3.3

  • In the PhoneModel.swift file, uncomment line 17 to add the 3 new cases for the newly announced iPhone models
  • Open the AutoCases.generated.swift file in another tab in Xcode to look at the code which was generated before that change
  • Start a Build, and see how the AutoCases.generated.swift file has been properly updated automatically, without any maintenance step from your end!

➡️ Next Steps