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.

Oscar de la Hera Gomez
Written by Oscar de la Hera Gomez
First published on 08/15/2024 at 13:48
Last Updated on 08/15/2024 at 16:02
<p>Two flowers that represents SwiftUI and XCode side by side with the text “Macros" beneath it.</p>

A tutorial that provides custom code for creating a Swift macro that checks for specific cases, defines variables and initializers in Swift and XCode.

Subscribe

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.

Download Open Source SwiftUI Starter Project

This macro was made possible thanks to the Apple WWDC sessions linked below.

Please review these sessions before continuing.

Apple: Write Swift Macros (WWDC23)Apple: Expand on Swift Macros (WWDC23)

The key elements that made this possible are:

Definitions

<p>A screenshot of the definitions of the Macros.</p>

To be able to define variables with arbitrary names, make sure to use the @attached(member, names: arbitrary).

Initializers

<p>A screenshot showing how to generate initializers in a macro.</p>

To define initializers use the InitializerDeclSyntax function.

Variables and Constants

<p>A screenshot showing how to generate variables using a macro.</p>

To declare variables or constants, use the VariableDeclSyntax function.

Tests

<p>A screenshot of the tests for the Macros.</p>

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.

Search our Blog

Any Questions?

We are actively looking for feedback on how to improve this resource. Please send us a note to inquiries@delasign.com with any thoughts or feedback you may have.
SubscribeContact UsVisit our BlogView our ServicesView our Work

Partner with us

We would love to get to know you and see how we can help your organization with its goals and needs.
Let's Talk

Stay Informed

Get occasional updates about our company, research, and product launches.
Subscribe