Swift Macros Cheat Sheet
Covers Swift 5.9+ macro types (freestanding/attached), writing macro declarations, SwiftSyntax expansion basics, and built-in macros like #Preview.
2 PagesAdvancedMar 3, 2026
Declaring a Macro
Macro declarations live in your app target; expansion logic lives in a separate compiler plugin target.
swift
// In your app/library target:@freestanding(expression)macro stringify<T>(_ value: T) -> (T, String) = #externalMacro(module: "MyMacros", type: "StringifyMacro")@attached(member, names: named(init))macro AddInit() = #externalMacro(module: "MyMacros", type: "AddInitMacro")// Usage:let (result, code) = #stringify(2 + 3)// result == 5, code == "2 + 3"
Implementing a Macro (Compiler Plugin)
Macros are implemented with SwiftSyntax against a `CompilerPlugin` target declared in Package.swift.
swift
import SwiftSyntaximport SwiftSyntaxMacrospublic struct StringifyMacro: ExpressionMacro { public static func expansion( of node: some FreestandingMacroExpansionSyntax, in context: some MacroExpansionContext ) throws -> ExprSyntax { guard let arg = node.arguments.first?.expression else { throw MacroError.missingArgument } return "(\(arg), \(literal: arg.description))" }}@mainstruct MyMacrosPlugin: CompilerPlugin { let providingMacros: [Macro.Type] = [StringifyMacro.self]}
Package.swift for a Macro Target
Macros require a `.macro` target plus a `CompilerPlugin` build product.
swift
let package = Package( name: "MyMacros", targets: [ .macro( name: "MyMacrosImpl", dependencies: [ .product(name: "SwiftSyntaxMacros", package: "swift-syntax"), .product(name: "SwiftCompilerPlugin", package: "swift-syntax"), ] ), .target(name: "MyMacros", dependencies: ["MyMacrosImpl"]), ])
Common Built-in Macros
Macros shipped with Swift/SwiftUI you'll use daily.
- #Preview- declares a SwiftUI preview without a PreviewProvider boilerplate
- #warning / #error- emit a compiler diagnostic at that source location
- #file, #line, #function- expression macros giving source location info
- @Observable- attached macro that generates observation tracking (replaces ObservableObject)
- @Model- SwiftData attached macro that turns a class into a persistent model
- #stringify- example freestanding macro pattern for expr + source text pairs
Pro Tip
Attached macros can only ADD code (members, accessors, conformances) — they can't remove or rewrite existing declarations, so design your macro's API assuming it's purely additive.
Was this cheat sheet helpful?
Explore Topics
#SwiftMacros#SwiftMacrosCheatSheet#Programming#Advanced#DeclaringAMacro#Implementing#Macro#Compiler#CheatSheet#SkillVeris
Advertisement
Sri Hayavadhana Info-Tech
Professional Web Designing Services
- Responsive Websites
- E-commerce Solutions
- SEO Friendly Design
- Fast & Secure
- Support & Maintenance