How to create a complex member Macro in Swift

Oscar de la Hera Gomez
Two flowers that represents SwiftUI and XCode side by side with the text “Macros" beneath it.

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

A screenshot of the definitions of the Macros.

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

Initializers

A screenshot showing how to generate initializers in a macro.

To define initializers use the InitializerDeclSyntax function.

Variables and Constants

A screenshot showing how to generate variables using a macro.

To declare variables or constants, use the VariableDeclSyntax function.

Tests

A screenshot of the tests for the Macros.

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.

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.
delasign logo

Book a Free Consultation.

An icon of an email.

Click here to email us.

Fill in the details below to book a free consultation or to let us know about something else. Whatever it is, we are here to help.

How can we help you ?

Contact Details