Member-only story
Mastering Swift Macro
With the release of Swift 5.9, Apple introduced a new feature called Macros. Macros allow you to generate code at compile time, helping you avoid repetitive code. The code is generated before your project is built, which may raise concerns about debugging. However, both the input and output (the code generated by the macro) are checked to ensure they are syntactically valid Swift code.
In the upcoming sections, we will discuss the different types of Macros, provide an example of how to implement your first Macro, explore cases where Macros can enhance our code, and demonstrate how we used them at Klivvr to eliminate boilerplate code.
For more of this subscribe to my newsletter . Where I share Swift tips that work in production, plus insights on personal growth and tech innovation. This newsletter is not just for iOS but for all the visionaries who dare to think differently — the ones who believe their code can change the world. 🌍
Types of Macros
- Freestanding Macros: Appear on their own without being attached to any declaration and start with
#
, such as#Error()
and#warning()
. - Attached Macros: Modify the declaration they are attached to, using the
@
symbol before the name of the Macro.
Freestanding Macros
There are two types of freestanding Macros:
- Expression Freestanding Macro: Used to create a piece of code that returns a value.