Photo by Heidi Fin on Unsplash

Shallow comparison of Swift Enum using Sourcery

Ryuichi / Rick
3 min readSep 21, 2022

--

Hi there, I’d like to show you how we can generate shallow comparisons automatically for Swift Enum, which I introduced for my team.

How do you write shallow comparisons manually?

Here is an enum which has some cases. And one has an associated value, but the other one doesn't.

Animal Enum

When you would like to check whether an enum variable is an intended one, how do you do?

If each enum-case doesn’t any associated values, it is so easy to compare self with one case. But if it does, you are required to use some redundant statement like if-case, guard-let :(

Originally, how do we write the shallow comparison?

If you write the boilerplate every single time, it must be the waste of the time. So, I recommend you to examine some tools as automatic generation!

Sourcery

Sourcery is such an awesome tool for us to cut the time to write boilerplate.

If you wanna know how to use it, you can get it thorough the link below!

And I’ll use this tool for working on generating a shallow comparison I’ve showed you.

Automatic generation of the shallow comparison using Sourcery

When you use Sourcery, you need to write a stencil code, which is used as a template. And by the stencil file below(Comparison.stencil), you can generate the output file automatically(Please look at Comparison.output.swift). Sourcery can check all codes you’ve specified in sourcery command.

Comparison.stencil
Comparison.output.swift

Thanks to this shallow comparison, you don’t need to write such a fiddly boilerplate! You can use like below(e.g. animal.isDog). Awesome!!

How we use shallow comparison, which is generated by Sourcery.

Some tips for stencil✈️

1. Annotation

By default, all codes you specified are checked and can be the target for automatic generation. But, you can remove enum from the target individually by adding an annotation.

How can we exclude which has a specified annotation?
How can we exclude which has a specified annotation?

Both of isDog and isBird will not be generated although they are target of checking by Sourcery👍

2. AccessLevel

If you don’t wanna generate from enum whose access level is private or file private, you can exclude them. By using the where condition, you can check the access level👍

How can we specify an access level in stencil file?

3. Enum, which has no cases

We don’t have to generate even the extension, so we should exclude the enum, which has no cases👍

How can we exclude the enum which has no cases?

Conclusion

Sourcery is such a great tool for reducing the boilerplate as much as possible so we can do better coding. And a shallow comparison for the enum is the useful way instead of writing the fiddly statements like guard-let, if-let. And such statements easily lead you to create bugs.

If you know another useful usage using Sourcery, please let me know!!

--

--