Writing a Freestanding Expression Macro
Implementing a simple #stringify macro with SwiftSyntax and MacroExpansion.
Project Setup
Macros live in a separate Swift package target of kind .macro, using SwiftSyntax.
// Package.swift (excerpt)
.macro(
name: "MyMacros",
dependencies: [
.product(name: "SwiftSyntaxMacros", package: "swift-syntax"),
.product(name: "SwiftCompilerPlugin", package: "swift-syntax")
]
)Macro Declaration
Declare the macro signature in a library target so clients can call it.
@freestanding(expression)
public macro stringify<T>(_ value: T) -> (T, String)
= #externalMacro(module: "MyMacros", type: "StringifyMacro")All lessons in this course
- Macro Roles: Freestanding vs Attached
- Writing a Freestanding Expression Macro
- Attached Member Macros for Boilerplate Reduction
- Testing and Debugging Macros