What a macro is, and what it is not
A Swift macro is a compiler plugin that receives part of your source as a syntax tree and returns new syntax that the compiler then type-checks like code you wrote by hand. The Swift book’s Macros chapter is careful about one rule: macros only add code. They never delete or modify the code you wrote. You already use them every day: @Observable, #Preview, #Predicate, @Model and the Swift Testing #expect are all macros.
Writing your own is a different decision. A macro adds a package, a plugin target and a dependency on swift-syntax, and it puts generated code in places a reader cannot see until they expand it. This guide covers when that trade is worth it, how the roles fit together, how to build a small macro, and what it does to your build.
When a macro earns its place
Antoine van der Lee’s macros overview is blunt that macros are an advanced feature and you do not need to write them to build apps. That is the right starting point. Reach for a macro in two situations:
- Compile-time validation. A literal that can be wrong, such as a URL, a hex color, a regex or an SF Symbol name, can be checked while compiling. The macro emits a real compiler error pointing at the bad argument, instead of a force unwrap that crashes at runtime.
- Boilerplate that the type system cannot express. Generating members from a type’s stored properties, adding a conformance with the same five methods to many types, or writing a mock for every protocol requirement. Functions and generics cannot see a type’s declarations. Macros can.
Do not write a macro when:
- A function, a generic or a protocol extension already does the job.
- A property wrapper would work. It is simpler, and readers know how it behaves.
- The generated code would be larger and harder to debug than what it replaces.
- It saves typing in one file. Macros pay off when they are applied many times.
The two families and their roles
Freestanding macros
Freestanding macros start with # and stand on their own.
@freestanding(expression)(SE-0382) produces a value:#hexColor("#FF9500"),#URL("https://example.com").@freestanding(declaration)(SE-0397) produces one or more declarations, such as a set of constants or a type.
Attached macros
Attached macros start with @ and apply to the declaration that follows (SE-0389). One macro can have several roles at once:
| Role | Adds |
|---|---|
peer |
Declarations next to the attached one, such as an async overload of a function |
member |
Members inside a type, such as an initializer or a static property |
memberAttribute |
Attributes on each member of a type, the way @Observable marks properties |
accessor |
get, set, willSet or didSet on a property |
extension |
An extension, optionally with a protocol conformance (SE-0402, replaced conformance) |
body |
The body of a function that was declared without one (SE-0415, Swift 6.0) |
Any declaration a macro adds that other code can refer to must be listed in the macro’s declaration, for example names: named(caseCount). The compiler uses that list to resolve names before it expands anything, which keeps expansion predictable and fast.
Building a macro
Package layout
swift package init --type macro creates the four pieces you need. In Xcode, File > New > Package with the Swift Macro template does the same. The parts are:
- A
.macrotarget with the implementation. It depends onSwiftSyntaxMacrosandSwiftCompilerPluginfrom swift-syntax and runs inside the compiler at build time, on your Mac. - A library target that declares the macro and is what your app imports.
- An optional client target to try it out.
- A test target.
The implementation is never linked into your app. Only the expanded code is.
Declaring the macro
The declaration in the library target names the implementation type:
import SwiftUI
@freestanding(expression)
public macro hexColor(_ hex: String) -> Color = #externalMacro(
module: "ColorMacrosPlugin",
type: "HexColorMacro"
)
@attached(member, names: named(caseCount))
public macro CaseCount() = #externalMacro(
module: "ColorMacrosPlugin",
type: "CaseCountMacro"
)
The module string must match the .macro target’s name exactly, and type must match the implementation type. A mismatch shows up as “external macro implementation type … could not be found”, a warning on the declaration and an error where the macro is used. It is the most common first-day problem.
Implementing an expression macro with validation
This implementation, written against swift-syntax 600 or later, reads a string literal, rejects anything that is not a six-digit hex value with a diagnostic on the argument, and returns a Color expression:
import SwiftSyntax
import SwiftSyntaxMacros
import SwiftDiagnostics
public struct HexColorMacro: ExpressionMacro {
public static func expansion(
of node: some FreestandingMacroExpansionSyntax,
in context: some MacroExpansionContext
) throws -> ExprSyntax {
guard
let argument = node.arguments.first?.expression,
let literal = argument.as(StringLiteralExprSyntax.self),
let text = literal.representedLiteralValue
else {
throw MacroExpansionErrorMessage("#hexColor needs a string literal like \"#FF9500\"")
}
let hex = text.hasPrefix("#") ? String(text.dropFirst()) : text
guard hex.count == 6, let value = UInt32(hex, radix: 16) else {
context.diagnose(Diagnostic(
node: argument,
message: MacroExpansionErrorMessage("\"\(text)\" is not a six-digit hex color")
))
return "Color.clear"
}
let red = Double((value >> 16) & 0xFF) / 255
let green = Double((value >> 8) & 0xFF) / 255
let blue = Double(value & 0xFF) / 255
return "Color(red: \(literal: red), green: \(literal: green), blue: \(literal: blue))"
}
}
Two details matter. representedLiteralValue returns nil for interpolated strings, so #hexColor("#\(variable)") is rejected with a clear message instead of failing somewhere in the expansion. And the expansion returns source text through ExprSyntax’s string interpolation, with \(literal:) for values so they are emitted as proper Swift literals. Writing syntax as interpolated source is much easier to read than building nodes by hand, and the compiler parses it for you.
Implementing a member macro
Attached macros receive the declaration they are attached to. This one counts the cases of an enum and adds a static property:
import SwiftSyntax
import SwiftSyntaxMacros
import SwiftDiagnostics
public struct CaseCountMacro: MemberMacro {
public static func expansion(
of node: AttributeSyntax,
providingMembersOf declaration: some DeclGroupSyntax,
conformingTo protocols: [TypeSyntax],
in context: some MacroExpansionContext
) throws -> [DeclSyntax] {
guard let enumDecl = declaration.as(EnumDeclSyntax.self) else {
throw MacroExpansionErrorMessage("@CaseCount can only be attached to an enum")
}
let count = enumDecl.memberBlock.members
.compactMap { $0.decl.as(EnumCaseDeclSyntax.self) }
.reduce(0) { $0 + $1.elements.count }
return ["static let caseCount = \(literal: count)"]
}
}
CaseIterable already gives you allCases.count, so in a real project this one fails the “do you need a macro” test. It is here because it shows the shape every attached macro shares: check what you were attached to, walk the syntax, return new declarations.
Registering the plugin
The .macro target needs one entry point that lists every macro it provides:
import SwiftCompilerPlugin
import SwiftSyntaxMacros
@main
struct ColorMacrosPlugin: CompilerPlugin {
let providingMacros: [any Macro.Type] = [
HexColorMacro.self,
CaseCountMacro.self,
]
}
At the use site:
import SwiftUI
import ColorMacros
let accent = #hexColor("#FF9500")
@CaseCount
enum Tab {
case home, search, library
}
ColorMacros is the library target from the declaration step. A typo such as #hexColor("#FF95") is now a compile error on that line.
Exploring the syntax tree
The hardest part of writing a macro is knowing which syntax node you are looking at. Antoine van der Lee suggests printing the node or using the Swift AST Explorer site to see the tree for a piece of source. In Xcode, right-click any macro use and choose Expand Macro to see exactly what it produced.
Testing
Macros are pure functions from syntax to syntax, which makes them easy to test, and the Swift book recommends developing them test-first. swift-syntax ships assertMacroExpansion for comparing input source with expected output and diagnostics. Point-Free’s swift-macro-testing adds assertMacro, which records the expansion into the test file for you, renders diagnostics and fix-its inline, and works with Swift Testing through a suite trait. Test the diagnostics as carefully as the happy path, since they are your macro’s user interface.
Build-time cost
Why macros slowed builds
A macro target depends on swift-syntax, a large package. Until recently every clean build compiled it from source before your macro could run, and in a release configuration that took a long time. On CI with no cache, that cost landed on every build. It is the most common complaint teams raise when they adopt a macro-heavy dependency.
Prebuilt swift-syntax
SwiftPM can now download a prebuilt swift-syntax instead. The forum preview from Doug Schaefer in May 2025 introduced it in Swift 6.1.1 and Xcode 16.4 as an opt-in: swift build --enable-experimental-prebuilts, or the Xcode user default IDEPackageEnablePrebuilts. The Swift 6.2 release post lists the feature as part of 6.2, so projects no longer have to build swift-syntax from source before building macros, which mostly helps clean builds and CI. Swift 6.3 extended it so helper libraries used only by macros can share the prebuilt swift-syntax as well.
The forum thread is clear about the limits:
- A prebuilt is used only when one exists for your exact resolved swift-syntax version, your compiler version and the host platform. Otherwise SwiftPM quietly builds from source.
- It covers macros. A target that uses swift-syntax for something else still builds it.
- If you suspect it is not being used, the thread’s advice is to clear
~/.swiftpm/cache/prebuiltsalong with.buildor the project’s DerivedData, and to check that your tools version is current.
To turn it off in Xcode, for example while diagnosing a build problem:
defaults write com.apple.dt.Xcode IDEPackageEnablePrebuilts NO
Keep swift-syntax versions in step
swift-syntax major versions follow the compiler: tags in the 600 series pair with Swift 6.0, 601 with 6.1, and so on up to 604. If your app has two macro packages that require incompatible swift-syntax ranges, resolution fails. When you publish a macro package, accept a wide range such as "600.0.0"..<"605.0.0" once you have checked it builds against each.
Traps and edge cases
- Trust prompt. Xcode asks you to trust and enable a macro package the first time you build it. On CI, builds fail until the macro is trusted or validation is skipped in the build command; set that up deliberately for packages you have reviewed.
- Sandboxing. SE-0382 runs macro implementations in a sandbox without file system or network access. A macro cannot read a JSON file from your project to generate code. Use a build tool plugin for that.
- No context outside the node. A macro sees the syntax it is attached to, not the rest of the file or other types. It cannot ask whether a type conforms to a protocol elsewhere.
- Diagnostics over crashes. Never
fatalErrorin an implementation. Emit a diagnostic with a message the user can act on, and a fix-it when the correction is obvious. - Generated code still has to compile under Swift 6 rules. If your expansion creates a
static var, it will trip strict concurrency checking in the client. Generatestatic letor isolated members. - Debugging is harder. Generated code lives in buffers you only see through Expand Macro. Keep expansions short and call into ordinary functions where you can, so most of the logic is code you can step through.
Checklist before writing one
| Question | If yes |
|---|---|
| Can a function, generic or protocol extension do it? | Do that instead |
| Would a property wrapper do it? | Use the property wrapper |
| Does it validate a literal at compile time? | Freestanding expression macro |
| Does it generate members from a type’s declarations? | Attached member, extension or memberAttribute |
| Does it need files, network or other types? | Build tool plugin or code generation, not a macro |
| Is it used in many places? | The build cost is likely worth it |
| Are your clean builds on CI slow? | Confirm prebuilt swift-syntax is in use |
Sources and further reading
- Macros The Swift Programming Language
- SE-0382: Expression Macros Swift Evolution
- SE-0389: Attached Macros Swift Evolution
- SE-0397: Freestanding Declaration Macros Swift Evolution
- Swift Macros: Extend Swift with New Kinds of Expressions Antoine van der Lee, SwiftLee
- swift-macro-testing Point-Free
- [Preview] Swift-Syntax Prebuilts for Macros Swift Forums
- Swift 6.2 Released swift.org
- Swift 6.3 Released swift.org