How many times how you copied and pasted some code in your current codebase because there was no good way to abstract it? Maybe because it was some repeating code required by a framework or mapping of some data transfer structures.
Writing such boilerplate code is an error-prone waste of time, especially when there is a much better way: generating that code.
There are a few tools to help you do that, one of the most flexible of them being GYB
.
What is GYB?
GYB
is a lightweight templating system that allows you to use Python
to generate text files. Those text files can be Swift
source code files or anything else you need.
GYB
is used in the Swift
standard library codebase so it works well for generating Swift
source code and it is a proven technology that works.
You can download GYB
to your project from the Swift
repository on Github
wget https://github.com/apple/swift/raw/master/utils/gyb
wget https://github.com/apple/swift/raw/master/utils/gyb.py
chmod +x gyb
I put it directly to the project directory and include it in the source control for simpler build and CI/CD setup.
Creating GYB templates
GYB
templates for generating Swift
source file look like Swift
source files with some Python
snippets for code generation.
This is probably best shown on an actual example. Let’s say you have a list of permissions that the app needs to support. Those permissions are then a part of a protocol and of a few structs.
[Read More]