Chuyển đến nội dung

Bài 72 · Protocols and Generics

Macros

Learn Swift macros: freestanding and attached macros, built-in ones like #fileID, #warning, @Observable and #Predicate, and how custom macros are built.

Some code is repetitive in a way no function or generic can fix. A Predicate needs the structure of the expression you wrote, not just its result. An observable model needs every property rewritten so that reads and writes are tracked. A test framework wants to print x + 1 == 5 along with the values on both sides. A function cannot see the source text of its arguments, and a generic cannot add properties to a type. A macro can: it is code that runs at compile time, receives a piece of your program as a syntax tree, and returns more Swift code that the compiler then compiles in its place.

Swift 5.9 introduced macros. You will meet them long before you write one: @Observable, #Predicate, #expect, @Model and #Preview are all macros. This lesson explains the two kinds, shows the ones that run in this tutorial's compiler, and then walks through how a custom macro is built, in read-only snippets, because writing a macro needs a separate package that a single-file program cannot contain.

How a macro works

The compiler does not run macros inside your program. It hands a syntax tree to a separate macro plugin, a small executable written in Swift with the swift-syntax library. The plugin returns new syntax, and the compiler inserts it, type-checks it like code you wrote, and the expansion is ordinary Swift, with no runtime magic.

Two rules make macros safe to use:

  • A macro can only add code to the place where you call it. It cannot reach into other files or change code you did not point it at.
  • Macros run in a sandbox with no network or file access, and the expansion is always visible: Xcode shows it, and swiftc -Xfrontend -dump-macro-expansions prints it.

You tell macros apart by their syntax. Calls start with # (freestanding) or @ (attached).

Freestanding macros: #name(...)

A freestanding macro stands on its own, like a function call. It produces either an expression (#Predicate, #expect, #fileID) or one or more declarations. Some freestanding macros are built into the compiler itself, and these are the oldest. You already know them as "magic literals".

Swift Compiler-provided # macros

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Three things deserve attention. First, default arguments such as #line and #function are expanded at the call site, so whereAmI() reports the caller's line, not its own. Inside work the function name is work(); at the top level it is the module name, which is binary in this runner. Second, #fileID and #file produce binary/main.swift (module plus file name) while #filePath gives the path the compiler was invoked with, main.swift. Third, #warning does not print anything at run time. It makes the compiler report warning: remember to handle errors, which appears in the "compiler warnings" part of the output.

Its sibling #error stops the build on purpose, which is useful in a conditional block to reject an unsupported configuration:

Swift #error stops compilation (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The compiler reports main.swift:1:8: error: this build is not supported, and the program never runs. These macros read the source position, which is why they are so good for logging and assertions: write #fileID as a default parameter and the caller's location arrives for free, as in the log(_:file:line:) pattern in Printing and Debugging.

Conditional compilation is not a macro

#if, #else, #endif look similar but belong to the compiler's own syntax, not the macro system. They check conditions before compiling, and the discarded branch only needs to parse.

Swift #if checks the compiler, the OS and the available modules

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

On this server you see Swift 6 or newer, compiler 6.2+, Linux, no SwiftUI and not debug. canImport is the safe way to write code that works on Apple platforms and elsewhere. DEBUG is a flag your build system defines; the runner does not.

A real freestanding macro: #Predicate

#Predicate comes with Foundation. You write a closure that looks like normal Swift, and the macro turns it into a data structure that describes the test. That structure can be inspected, translated to SQL by a database layer, or evaluated in memory.

Swift #Predicate builds a value from a closure

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The output is ["pen"] and then ["book"]. A normal closure { $0.price < 5 } would already work with filter; the point of a predicate is that it is a description, so a database framework could read it. Because the macro must understand every operation, it supports only a documented subset of Swift. Anything else is a compile-time error from the macro:

Swift An unsupported operation in a predicate (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The message is error: The squareRoot() function is not supported in this predicate (from macro 'Predicate'). Note (from macro 'Predicate'): diagnostics from a macro name the macro that produced them. The macro author controls those messages, which is a big advantage over the cryptic template errors of older approaches.

Attached macros: @Name

An attached macro is written as an attribute on a declaration and adds to that declaration: new members in a type, accessors on a property, extra conformances, or peer declarations next to it. The best-known one is @Observable from the Observation module. Mark a class and its stored properties become tracked: reading one inside withObservationTracking registers interest, and a change calls you back once.

Swift @Observable and withObservationTracking

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

You see tracking 0, then ignored property changed: no callback, then first change, then final 2. The callback ran exactly once, even though value changed twice: observation is one-shot per tracking call, and you re-register if you want more. The property marked @ObservationIgnored never notified anyone.

Behind the scenes @Observable expands to roughly this (shortened, read-only):

Swift
// Read-only: simplified view of what the macro adds to Counter.
final class Counter: Observable {
    internal let _$observationRegistrar = ObservationRegistrar()

    var value: Int {
        get {
            access(keyPath: \.value)
            return _value
        }
        set {
            withMutation(keyPath: \.value) { _value = newValue }
        }
    }
    private var _value = 0
    // plus access/withMutation helper methods
}

Each stored property becomes a computed property that tells a registrar about reads and writes, and the original storage moves to a hidden _value. Without the macro you would write that by hand for every property of every model. If you forget the import, the attribute does not exist:

Swift Using @Observable without importing Observation (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The compiler answers error: unknown attribute 'Observable'. Macros are declared in modules like any other API, so you must import the module that declares them.

The attached macro roles are @attached(member) (add members), @attached(accessor), @attached(memberAttribute), @attached(peer), @attached(extension) (add conformances) and @attached(body). A single macro such as @Observable often combines several roles.

Testing macros: #expect

The new Swift Testing framework is built on macros. #expect(a == b) captures the expression so a failure can print both sides, something a plain function expect(a == b) could never do because it only receives false. It is meant to run inside a test function marked @Test, which the lesson Testing in Swift explains. Outside a test run nothing records the result, so a failing expectation is silent:

Swift #expect outside a test run

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

This is a useful reminder: a macro changes how the code is compiled, not when your program decides to run it.

Writing your own macro (read-only)

A custom macro needs three files in a Swift package, which is why it cannot run in our single-file sandbox. If you try to use a macro whose implementation does not exist, the compiler tells you:

Swift A macro without a plugin (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

You get error: external macro implementation type 'MyMacros.StringifyMacro' could not be found for macro 'stringify'; plugin for module 'MyMacros' not found. The declaration (macro stringify...) only names an implementation; the implementation lives in a separate module. Here is the implementation, as a read-only example:

Swift
// Read-only example: Sources/MyMacros/StringifyMacro.swift (needs swift-syntax)
import SwiftSyntax
import SwiftSyntaxMacros

public struct StringifyMacro: ExpressionMacro {
    public static func expansion(
        of node: some FreestandingMacroExpansionSyntax,
        in context: some MacroExpansionContext
    ) throws -> ExprSyntax {
        guard let argument = node.arguments.first?.expression else {
            throw MacroError.message("#stringify needs one argument")
        }
        return "(\(argument), \(literal: argument.description))"
    }
}

The macro receives the call as a syntax tree (node), picks out the argument, and returns new syntax: a tuple with the original expression and its source text as a string literal. With a package whose Package.swift declares a .macro target (see Swift Package Manager), #stringify(1 + 2) produces (3, "1 + 2").

When to use macros, and when not to

Reach for the macros that exist: @Observable, #Predicate, #expect. Write your own only when:

  • the same boilerplate repeats across many types and cannot be a protocol default or generic;
  • you need the source text or structure of an expression;
  • you want a compile-time check with a clear error message.

Avoid macros for things a function, a protocol extension or a property wrapper handles. Macros cost build time (the plugin must be built, and swift-syntax is large), make stack traces and debugging harder to read, and hide code. They are best treated as an advanced tool.

Check your understanding

Quick check · 5 questions

of 5 answered You scored / 5 · perfect!

  1. 1. What does a Swift macro return to the compiler?

    A macro runs at compile time, receives syntax and returns syntax. The result is type-checked like code you wrote.
  2. 2. Which of these is an attached macro?

    Attached macros are written as attributes (@Name) on a declaration; freestanding macros start with #.
  3. 3. Why does whereAmI() with line: Int = #line report the caller's line?

    The compiler substitutes the literal where the call is written, which makes these defaults perfect for logging.
  4. 4. What happens if you use @Observable without import Observation?

    Macros are declared in modules. Without the import the compiler does not know the name.
  5. 5. Which statement about #if canImport(SwiftUI) is true?

    #if is part of the language's syntax for conditional compilation, not a macro.

Summary

  • A macro is compile-time code that receives syntax and returns more Swift code; the expansion is ordinary, type-checked Swift.
  • Freestanding macros start with # (#Predicate, #expect, #fileID, #warning, #error); attached macros start with @ (@Observable).
  • Magic literals used as default arguments report the caller's location.
  • #if is conditional compilation, not a macro.
  • @Observable rewrites stored properties to report reads and writes; withObservationTracking notifies once per registration.
  • #Predicate understands only a subset of Swift and reports unsupported code as compile errors that name the macro.
  • Custom macros live in a separate package built on swift-syntax and cannot run in a single main.swift.
  • Use existing macros freely; write your own only for boilerplate that nothing else can remove.

Next: Error Handling

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.