The Case of the Vanishing Bodies
An Introduction to Swift Macros
"I'm not sure that anyone should be writing their own Swift Macros, but if you've decided to go ahead and do it, this is the book for you."
- A mostly satisfied reader
While everyone who writes Swift code will use Swift Macros, not everyone should write their own Swift Macros. This book will help you determine whether writing Swift Macros is for you and show you how the best ways to make your own.
You'll create both freestanding and attached macros and 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.3 and Swift 5.10 and tested on Apple Silicon.
Contents
- 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
- Credits
- 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
- Diagnostics
- 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
- FixIts
- 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