5.5 · How Swift macros work, and the roles they play

Macros generate Swift code at compile time. The one-line comparison with property wrappers and result builders is covered in the language section; this one is about the machinery, its limits and its price.

Mental model. A macro is a small compiler plugin that rewrites syntax into more syntax. It sees the text of what you wrote, never the types, and its output is compiled like code you typed yourself.

How a macro runs

The plugin model, its sandbox, and what it costs.

  1. How does a Swift macro actually run, what can it not do, and what does it cost? 5.5.1 · L5
    A macro is implemented as a compiler plugin: a separate executable built with SwiftSyntax. When the compiler meets a macro use it launches the plugin, sends it…

What macros can add

Freestanding and attached roles.

  1. What are the macro roles, and which real macros use which? 5.5.2 · L5
    A macro declares roles that say where it may appear and what it may produce. Freestanding macros are written with a # and stand alone: an expression macro…

More in Compiler & language internals