How to create a complex member Macro in Swift
A tutorial that provides custom code for creating a Swift macro that checks for specific cases, defines variables and initializers in Swift and XCode.
The code for this tutorial can be found within the Macros/StringJSON folder on the main branch of our Open Source SwiftUI starter project available below.
This macro was made possible thanks to the Apple WWDC sessions linked below.
Please review these sessions before continuing.
The key elements that made this possible are:
Definitions
To be able to define variables with arbitrary names, make sure to use the @attached(member, names: arbitrary).
Initializers
To define initializers use the InitializerDeclSyntax function.
Variables and Constants
To declare variables or constants, use the VariableDeclSyntax function.
Tests
We have made sure the Macro only works if it passes all the tests. If not it will throw errors. These cases are the following:
@StringJSONParent must:
- Be a struct.
- Confirm to a codable struct.
- Have at least one child
- Have only structs that confirm to the @StringJSONChild protocol.
- Can only have children that confirm to the @StringJSONChild macro.
@StringJSONChild must:
- Be a struct.
- Confirm to a codable struct.
- Have at least one string.
- Cannot hold anything other than string variables.
- Only have string variables.
Looking to learn more about SwiftUI, Swift, Design and Technology?
Search our blog to learn more about Swift, SwiftUI, design and technology.