Macros
suggest changeA Swift macro generates code at compile time. You write #name(...) or @Name in your source, and the compiler replaces it with the code the macro produces before type checking the result. Macros were added in Swift 5.9 (SE-0382 expression macros, SE-0389 attached macros, SE-0397 declaration macros). Swift 6.0 added body macros (SE-0415).
Macros are not text substitution like C's #define:
- A macro gets a syntax tree of its arguments (or of the declaration it's attached to) and returns a new syntax tree.
- Arguments are type checked before expansion, and the expanded code is type checked again.
- A macro can only add code. It can't delete or rewrite the code you wrote.
- The expansion is ordinary Swift. You can print it and read it.
This article has two parts: using macros that ship with Swift, and writing your own with a Swift package.
The examples were compiled and run with Swift 6.4.1 on Windows:
swiftc -swift-version 6 main.swift -o main.exe
Two kinds of macros
Freestanding macros start with # and stand on their own like an expression or a declaration:
let line = #line
#warning("TODO: remove debug logging")
Attached macros start with @, like attributes, and are attached to a declaration. They add code to it:
@Observable
final class Counter {
var count = 0
}
Each macro has one or more roles that say where it can appear and what it may produce:
| Role | Spelling | Produces |
|---|---|---|
@freestanding(expression) |
#stringify(x) |
an expression |
@freestanding(declaration) |
#warning("...") |
zero or more declarations |
@attached(peer) |
@AddAsync func f() |
declarations next to the one it's attached to |
@attached(member) |
@CaseDetection enum E |
new members inside a type |
@attached(memberAttribute) |
@Observable |
attributes added to existing members |
@attached(accessor) |
@ObservationTracked var x |
get / set / init accessors for a property |
@attached(extension) |
@Observable |
an extension, usually adding a conformance |
@attached(body) (6.0) |
@Logged func f() |
the body of a function |
One macro can have several roles. @Observable is a member, memberAttribute and extension macro at the same time.
Using built-in macros
Several things that look like old compiler keywords are now macros declared in the standard library: #file, #fileID, #filePath, #line, #column, #function, #dsohandle, #warning, #error, #isolation (6.0) and #externalMacro. Other modules ship macros too: Observation has @Observable, Foundation has #Predicate, the standard library has @DebugDescription (6.0), and Swift Testing has #expect, #require and @Test (covered in the "Swift Testing: @Test and #expect" article).
import Foundation
import Observation
func log(_ message: String, file: String = #fileID, line: Int = #line,
function: String = #function) {
print("[\(file):\(line) \(function)] \(message)")
}
func load() {
log("loading")
}
load()
#warning("TODO: remove debug logging")
@Observable
final class Counter {
var count = 0
@ObservationIgnored var label = "clicks"
}
let counter = Counter()
withObservationTracking {
print("count is", counter.count)
} onChange: {
print("count will change")
}
counter.count += 1
counter.label = "taps" // ignored, no notification
print(counter.count)
struct Person { var name: String; var age: Int }
let adults = #Predicate<Person> { $0.age >= 18 }
let people = [Person(name: "Ada", age: 36), Person(name: "Tim", age: 12)]
print(try people.filter(adults).map(\.name))
Compiling prints the warning that #warning produced:
main.swift:14:10: warning: TODO: remove debug logging
12 | load()
13 |
14 | #warning("TODO: remove debug logging")
| `- warning: TODO: remove debug logging
15 |
16 | @Observable
Running it prints:
[main/main.swift:10 load()] loading
count is 0
count will change
1
["Ada"]
Notes:
#fileID,#lineand#functionused as default argument values expand at the call site. That's whylogreportsload()and notlog(_:file:line:function:).#warningand#errorare freestanding declaration macros.#error("...")stops the build. Both are handy inside#ifblocks.#Predicateturns a closure into aPredicate<Person>value, a tree of expressions that libraries such as SwiftData can translate into a database query. With plain arrays you just callfilter.@DebugDescriptionon a type with adebugDescriptionproperty makes LLDB show that string in the debugger. It doesn't change whatprintshows.
Seeing what a macro expands to
In Xcode, right-click a macro use and pick Expand Macro to see the generated code inline. On the command line, pass -dump-macro-expansions to the compiler frontend:
// obs.swift
import Observation
@Observable
final class Counter {
var count = 0
}
swiftc -swift-version 6 obs.swift -Xfrontend -dump-macro-expansions
The output (shortened) shows each expansion with a generated file name. Here is what @Observable added:
@__swiftmacro_3obs7Counter10ObservablefMm_.swift
------------------------------
@ObservationIgnored private let _$observationRegistrar = Observation.ObservationRegistrar()
internal nonisolated func access<...>(keyPath: KeyPath<Counter, ...>) {
_$observationRegistrar.access(self, keyPath: keyPath)
}
internal nonisolated func withMutation<...>(...) rethrows -> ... {
try _$observationRegistrar.withMutation(of: self, keyPath: keyPath, mutation)
}
...
------------------------------
@__swiftmacro_3obs7CounterC5count10ObservablefMr_.swift
------------------------------
@ObservationTracked
------------------------------
@__swiftmacro_3obs7CounterC5count18ObservationTrackedfMp_.swift
------------------------------
@ObservationIgnored
private var _count = 0
------------------------------
@__swiftmacro_3obs7CounterC5count18ObservationTrackedfMa_.swift
------------------------------
{
@storageRestrictions(initializes: _count)
init(initialValue) {
_count = initialValue
}
get {
access(keyPath: \.count)
return _count
}
set {
guard shouldNotifyObservers(_count, newValue) else {
_count = newValue
return
}
withMutation(keyPath: \.count) {
_count = newValue
}
}
...
}
------------------------------
@__swiftmacro_3obs7Counter10ObservablefMe_.swift
------------------------------
extension Counter: nonisolated Observation.Observable {
}
This shows how roles work together:
- The member role (
fMm_) adds the registrar and the helper methods. - The memberAttribute role (
fMr_) puts@ObservationTrackedoncount. That's another macro, and it expands too. @ObservationTrackedis a peer macro (fMp_) that adds the backing_countstorage, and an accessor macro (fMa_) that turnscountinto a computed property which reports reads and writes.- The extension role (
fMe_) adds theObservableconformance.
When a macro does something surprising, expanding it is the fastest way to find out why.
Writing a macro: the package layout
A macro is implemented as a compiler plugin, a separate program that the compiler runs during the build. It talks to the compiler using the swift-syntax library. You need a Swift package for this. SwiftPM has a template:
mkdir Stringify
cd Stringify
swift package init --type macro --name Stringify
Creating macro package: Stringify
Creating Package.swift
Creating .gitignore
Creating Sources
Creating Sources\Stringify\Stringify.swift
Creating Sources\StringifyMacros\StringifyMacro.swift
Creating Sources\StringifyClient\main.swift
Creating Tests/
Creating Tests\StringifyTests/
Creating Tests\StringifyTests\StringifyTests.swift
There are four targets:
StringifyMacrosis the macro implementation. It's a.macrotarget, built for the machine running the compiler, and depends on swift-syntax.Stringifyis the library that declares the macros. Users import it. It depends onStringifyMacrosonly so the build knows to compile the plugin first. The plugin isn't linked into your program.StringifyClientis an example program that uses the macros.StringifyTeststests the expansions.
The important part of Package.swift (swift-syntax resolved to 604.0.0 for Swift 6.4):
// swift-tools-version: 6.4
import PackageDescription
import CompilerPluginSupport
let package = Package(
name: "Stringify",
platforms: [.macOS(.v13), .iOS(.v16)],
products: [
.library(name: "Stringify", targets: ["Stringify"]),
.executable(name: "StringifyClient", targets: ["StringifyClient"]),
],
dependencies: [
.package(url: "https://github.com/swiftlang/swift-syntax.git", from: "604.0.0-latest"),
],
targets: [
.macro(
name: "StringifyMacros",
dependencies: [
.product(name: "SwiftSyntaxMacros", package: "swift-syntax"),
.product(name: "SwiftCompilerPlugin", package: "swift-syntax"),
]
),
.target(name: "Stringify", dependencies: ["StringifyMacros"]),
.executableTarget(name: "StringifyClient", dependencies: ["Stringify"]),
.testTarget(
name: "StringifyTests",
dependencies: [
"StringifyMacros",
.product(name: "SwiftSyntaxMacrosTestSupport", package: "swift-syntax"),
]
),
]
)
The template generates older platforms values that Swift 6.4 marks as deprecated, so they were raised here. The macro and its plugin build fine on Windows. The first swift run needs network access to fetch swift-syntax. SwiftPM downloaded a prebuilt swift-syntax bundle into .build/prebuilts, and the first build still took about a minute. After that, builds are incremental. For more on packages in general, see Creation and usage of a simple Swift package.
Declaring macros
The declarations in Sources/Stringify/Stringify.swift look like function signatures. #externalMacro tells the compiler which plugin module and type implement each one:
import Foundation
@freestanding(expression)
public macro stringify<T>(_ value: T) -> (T, String) =
#externalMacro(module: "StringifyMacros", type: "StringifyMacro")
@freestanding(expression)
public macro url(_ string: String) -> URL =
#externalMacro(module: "StringifyMacros", type: "URLMacro")
@attached(member, names: arbitrary)
public macro CaseDetection() =
#externalMacro(module: "StringifyMacros", type: "CaseDetectionMacro")
- The signature is type checked at the use site, so
#url(42)is an error before the plugin ever runs. - An attached macro has to declare the names it introduces.
names: named(foo)lists exact names,names: prefixed(is)allows names starting with a prefix, andnames: arbitraryallows any name. The compiler uses this to look up names without expanding every macro. - Freestanding macros are by convention lowercase (
#url), attached macros are capitalized (@CaseDetection), like types.
Implementing the macros
The implementation in Sources/StringifyMacros/StringifyMacro.swift is a set of types that conform to a protocol for their role. Each one gets the syntax of the macro use and returns new syntax:
import Foundation
import SwiftCompilerPlugin
import SwiftSyntax
import SwiftSyntaxBuilder
import SwiftSyntaxMacros
public struct StringifyMacro: ExpressionMacro {
public static func expansion(
of node: some FreestandingMacroExpansionSyntax,
in context: some MacroExpansionContext
) -> ExprSyntax {
guard let argument = node.arguments.first?.expression else {
fatalError("compiler bug: the macro does not have any arguments")
}
return "(\(argument), \(literal: argument.description))"
}
}
The return value is written as a string literal, but it's not a string. ExprSyntax conforms to ExpressibleByStringInterpolation from SwiftSyntaxBuilder, and the text is parsed into a syntax tree. The interpolations are special:
\(argument)inserts a syntax node as code.\(literal: value)inserts a correctly escaped Swift literal, here the source text of the argument as a string.\(raw: text)inserts text as code without escaping. Use it for identifiers you've built yourself.
Validating at compile time
A macro can throw. The error becomes a compiler error at the macro's location. #url checks the URL while compiling, so the force unwrap in the generated code can't fail at runtime:
enum URLMacroError: Error, CustomStringConvertible {
case notAStringLiteral
case invalidURL(String)
var description: String {
switch self {
case .notAStringLiteral: "#url requires a static string literal"
case .invalidURL(let s): "'\(s)' is not a valid absolute URL"
}
}
}
public struct URLMacro: ExpressionMacro {
public static func expansion(
of node: some FreestandingMacroExpansionSyntax,
in context: some MacroExpansionContext
) throws -> ExprSyntax {
guard let literal = node.arguments.first?.expression.as(StringLiteralExprSyntax.self),
let text = literal.representedLiteralValue else {
throw URLMacroError.notAStringLiteral
}
guard let url = URL(string: text), url.scheme != nil, url.host != nil else {
throw URLMacroError.invalidURL(text)
}
return "Foundation.URL(string: \(literal))!"
}
}
representedLiteralValue is nil for a string with interpolation, because its value isn't known at compile time. The macro only sees source code, never runtime values.
An attached member macro
@CaseDetection adds an isX property for every case of an enum:
public struct CaseDetectionMacro: MemberMacro {
public static func expansion(
of node: AttributeSyntax,
providingMembersOf declaration: some DeclGroupSyntax,
conformingTo protocols: [TypeSyntax],
in context: some MacroExpansionContext
) throws -> [DeclSyntax] {
guard declaration.is(EnumDeclSyntax.self) else {
throw MacroExpansionErrorMessage("@CaseDetection can only be applied to an enum")
}
let names = declaration.memberBlock.members
.compactMap { $0.decl.as(EnumCaseDeclSyntax.self) }
.flatMap { $0.elements }
.map { $0.name.text }
return names.map { name in
let capitalized = name.prefix(1).uppercased() + name.dropFirst()
return """
var is\(raw: capitalized): Bool {
if case .\(raw: name) = self { true } else { false }
}
"""
}
}
}
@main
struct StringifyPlugin: CompilerPlugin {
let providingMacros: [Macro.Type] = [
StringifyMacro.self,
URLMacro.self,
CaseDetectionMacro.self,
]
}
The macro walks the enum's syntax: members, then case declarations, then the elements of each case (one case a, b line has two). MacroExpansionErrorMessage is a ready-made error type from SwiftSyntaxMacros. The @main type lists every macro the plugin provides. The compiler starts the plugin and asks it for expansions by type name.
Using the macros
Sources/StringifyClient/main.swift:
import Foundation
import Stringify
let a = 17
let b = 25
let (result, code) = #stringify(a * 2 + b)
print("\(code) = \(result)")
let home = #url("https://www.programming-books.io/essential/swift")
print(home.host() ?? "-", home.path())
@CaseDetection
enum Shape {
case circle(radius: Double)
case square(side: Double)
case point
}
let shapes: [Shape] = [.circle(radius: 1), .point, .square(side: 2)]
print(shapes.map(\.isCircle))
print(shapes.filter(\.isPoint).count)
swift run StringifyClient
a * 2 + b = 59
www.programming-books.io /essential/swift
[true, false, false]
1
Dumping the expansions of this file shows exactly what the plugin produced:
(a * 2 + b, "a * 2 + b")
------------------------------
Foundation.URL(string: "https://www.programming-books.io/essential/swift")!
------------------------------
var isCircle: Bool {
if case .circle = self {
true
} else {
false
}
}
var isSquare: Bool {
...
}
var isPoint: Bool {
...
}
Now some incorrect uses:
let bad = #url("not a url")
let host = "example.com"
let dynamic = #url("https://\(host)")
@CaseDetection
struct NotAnEnum {}
swift build reports the errors the macros threw, at the right lines:
main.swift:23:11: error: 'not a url' is not a valid absolute URL (from macro 'url')
23 | let bad = #url("not a url")
| `- error: 'not a url' is not a valid absolute URL (from macro 'url')
main.swift:25:15: error: #url requires a static string literal (from macro 'url')
25 | let dynamic = #url("https://\(host)")
| `- error: #url requires a static string literal (from macro 'url')
main.swift:27:1: error: @CaseDetection can only be applied to an enum (from macro 'CaseDetection')
27 | @CaseDetection
| `- error: @CaseDetection can only be applied to an enum (from macro 'CaseDetection')
For finer control (warnings, notes, Fix-It suggestions), call context.diagnose(...) instead of throwing.
Testing macros
Macro implementations are plain functions from syntax to syntax, so you can test them without compiling a client. assertMacroExpansion from SwiftSyntaxMacrosTestSupport expands a source string and compares the result:
import SwiftSyntaxMacros
import SwiftSyntaxMacrosTestSupport
import XCTest
#if canImport(StringifyMacros)
import StringifyMacros
let testMacros: [String: Macro.Type] = [
"stringify": StringifyMacro.self,
"url": URLMacro.self,
"CaseDetection": CaseDetectionMacro.self,
]
#endif
final class StringifyTests: XCTestCase {
func testStringify() throws {
#if canImport(StringifyMacros)
assertMacroExpansion(
"#stringify(a + b)",
expandedSource: #"(a + b, "a + b")"#,
macros: testMacros
)
#else
throw XCTSkip("macros are only supported when running tests for the host platform")
#endif
}
func testInvalidURL() throws {
#if canImport(StringifyMacros)
assertMacroExpansion(
#"#url("not a url")"#,
expandedSource: #"#url("not a url")"#,
diagnostics: [
DiagnosticSpec(message: "'not a url' is not a valid absolute URL",
line: 1, column: 1)
],
macros: testMacros
)
#else
throw XCTSkip("macros are only supported when running tests for the host platform")
#endif
}
func testCaseDetection() throws {
#if canImport(StringifyMacros)
assertMacroExpansion(
"""
@CaseDetection
enum Light {
case on, off
}
""",
expandedSource: """
enum Light {
case on, off
var isOn: Bool {
if case .on = self {
true
} else {
false
}
}
var isOff: Bool {
if case .off = self {
true
} else {
false
}
}
}
""",
macros: testMacros
)
#else
throw XCTSkip("macros are only supported when running tests for the host platform")
#endif
}
}
swift test
Test Case 'StringifyTests.testCaseDetection' passed (0.01 seconds)
Test Case 'StringifyTests.testInvalidURL' passed (0.001 seconds)
Test Case 'StringifyTests.testStringify' passed (0.002 seconds)
Test Suite 'StringifyTests' passed at 2026-10-18 01:02:08.268
Executed 3 tests, with 0 failures (0 unexpected) in 0.012 (0.012) seconds
The expected source must match the expansion after formatting. swift-syntax reformats generated code, so the one-line if case .on = self { true } else { false } from the macro comes out split over several lines. When a test fails, the message prints the actual expansion, and you can copy it from there. The attribute itself (@CaseDetection) is removed from the expanded source.
Limits and good practice
- Macros only see syntax. They don't know types, so
@CaseDetectioncan't tell whatShapeconforms to unless the conformance is written on the declaration. Use them for code you'd otherwise write by hand from what's in the source. - Generated names can collide. Use
context.makeUniqueName("tmp")for local helper variables inside an expansion. - Plugins are sandboxed on macOS: no file system or network access. Make expansions depend only on their input.
- Third-party macros need trust. Xcode asks you to enable a macro package before the first use, because the plugin runs as a program on your machine. In CI,
xcodebuild -skipMacroValidationskips the prompt. - Build time. Every package that uses a macro depends on swift-syntax. Recent SwiftPM versions download a prebuilt swift-syntax, which helps, but macros still add some build cost.
- Prefer simpler tools first. A generic function, a protocol extension or a property wrapper is easier to read and debug. Reach for a macro when you need to see the source text (
#stringify), check something at compile time (#url), or generate members from a declaration (@CaseDetection,@Observable).
Macros generate code at compile time. For inspecting values at runtime, see Reflection.