The Case of the Vanishing Bodies

An Introduction to Swift Macros

The Case of the Vanishing Bodies

"The Case of the Vanishing Bodies" is an introduction to the magic of freestanding and attached Swift Macros.

There's a fair amount of boilerplate code involved in so many of our everyday tasks as Swift programmers. Until Xcode 15, every time we created a new SwiftUI View we had to create the corresponding preview code. The struct and computed property weren't interesting in any way - they were just a necessary task we needed to perform to display a preview of our View. With the introduction of the #Preview macro, we now only need to provide the code required to create an instance of the view being displayed.

In this book you'll learn to create a variety of macros. You'll get a feel for when you should and shouldn't create them, which sort of macro you should create, and how to use SwiftSyntax to implement them. Your macros will accept parameters when appropriate and will always include tests. You'll even learn to create helpful diagnostics for your macros and even FixIts.

Updated for Xcode 15 and Swift 5.10 and tested on Apple Silicon.


Prelude: Before we Begin

Chapter 1: A Look Around

Perhaps we can give it a try

Tale of Two Macros

The Model Macro

The Xcode Macro Template

Road Map


Chapter 2: Our First Macro

Naming the Macro

Defining the Macro

Passing Tests

Adding a Second Parameter

Manipulating Strings

Accessing Values Using ASTs

Introducing SwiftSyntax

Chapter 3: Freestanding Macros

URL: You do it

Throwing Errors

Using Macros in Projects

Using Macros in Macros

Declaration Macros

Helper Methods


Chapter 4: Our First Attached Macro

Explaining our goal

Seeing is not believing

Introducing an Attached Macro

Parameters for Expanding

Adding Flexibility to our Macro

More Diagnostics


Chapter 5: More Attached Macros

Macros and the Three Bears

Extension Macros

Accessor Macros

Peer Macros

Identifying Stored Properties

Combining Macros

MemberAttribute Macros

Presenting Macros in Macros


Swift Macros Training from Dim Sum Thinking