In Swift, how do freestanding `#` macros differ from attached `@` macros, and which roles can each kind declare?
answer
- where the call is written
- @freestanding vs @attached on the declaration
- expression or declaration, only one
- peer, member, memberAttribute, accessor, extension, body
- names: lists what gets introduced
basics
~20 sA freestanding macro is called with # on its own and has one role, expression or declaration. An attached macro is written as @Name on a declaration and adds code through peer, member, memberAttribute, accessor, extension or body roles.
solid answer
~40 sThe macro's declaration says which kind it is. `@freestanding(expression)` produces a value at the call site, as `#checkedURL("…")` does, and `@freestanding(declaration)` produces declarations; a macro may carry only one freestanding role. An attached macro is applied like an attribute, `@AddCompletionHandler func …`, and may list several `@attached` roles: `peer` adds declarations beside the one it is on, `member` adds members to a type or extension, `memberAttribute` adds attributes to those members, `accessor` turns a stored property into a computed one, `extension` adds an extension with conformances, and `body` (Swift 6.0) supplies a function's body. Peer and member roles list the names they introduce with `names:` (`named`, `overloaded`, `prefixed`, `suffixed`, `arbitrary`), and each role maps to a SwiftSyntax protocol such as `PeerMacro`.
code
swift · 27 linesimport Foundation
// Freestanding: called with #, exactly one freestanding role.
@freestanding(expression)
public macro checkedURL(_ string: String) -> URL =
#externalMacro(module: "MyMacros", type: "CheckedURLMacro")
// Attached: written as @Name on a declaration, one @attached per role.
@attached(peer, names: overloaded)
public macro AddCompletionHandler() =
#externalMacro(module: "MyMacros", type: "AddCompletionHandlerMacro")
@attached(extension, conformances: Equatable)
public macro AutoEquatable() =
#externalMacro(module: "MyMacros", type: "EquatableStubMacro")
@AutoEquatable
struct Endpoint {
let url = #checkedURL("https://example.com/feed")
@AddCompletionHandler
func load() async -> String { url.absoluteString }
}
print(Endpoint() == Endpoint()) // true: the extension macro added Equatable
Endpoint().load { print($0) } // the peer macro added load(completionHandler:)
Thread.sleep(forTimeInterval: 0.2)go deeper
Recall that # macros stand alone and @ macros sit on a declaration, and name one example of each from code you have read.
Explain each attached role by where its code lands, and why peer and member roles must declare the names they introduce.
Pick the role from the code you need to add and know the diagnostics: a name not covered, a second freestanding role, an accessor macro on a let.
Set which roles in-house macros may use; roles that add conformances, accessors or bodies change behaviour less visibly than a peer that only adds an overload.
## Two ways to use a macro Every Swift macro is declared with the `macro` keyword plus one or more **role attributes**, and the role decides both where the macro may be written and what it may produce. - A **freestanding** macro, declared with `@freestanding(...)`, is written on its own with a leading `#`: `#checkedURL("https://example.com")`, `#line`, `#warning("…")`. - An **attached** macro, declared with `@attached(...)`, is written like an attribute on a declaration: `@AddCompletionHandler func fetchAvatar(id:) async -> String`. It receives that declaration's syntax and adds code relative to it. By convention freestanding macros get lower-camel-case names, like functions, and attached macros upper-camel-case names, like types. ## Freestanding roles | Role | Produces | SwiftSyntax protocol | |---|---|---| | `expression` | a value at the call site; the declaration has a result type | `ExpressionMacro` | | `declaration` | one or more declarations where the call is written | `DeclarationMacro` | A macro may carry **only one freestanding role**; declaring both fails with `macro can only have a single freestanding role`. Only an expression macro may have a result type. ## Attached roles | Role | What it adds | SwiftSyntax protocol | |---|---|---| | `peer` | declarations beside the one it is attached to, in the same scope | `PeerMacro` | | `member` | members inside the type or extension it is attached to | `MemberMacro` | | `memberAttribute` | attributes on the members of that type or extension | `MemberAttributeMacro` | | `accessor` | accessors on a stored property, turning it into a computed one | `AccessorMacro` | | `extension` | an extension with protocol conformances, a `where` clause and members | `ExtensionMacro` | | `body` (Swift 6.0) | the body of the function or accessor it is attached to | `BodyMacro` | An attached macro may combine roles: write one `@attached` attribute per role. The book's `@OptionSet` example uses `@attached(member, …)` to add `rawValue` and the option constants and `@attached(extension, conformances: OptionSet)` to add the conformance, and its implementation type conforms to both `MemberMacro` and `ExtensionMacro`. The old `conformance` role is gone; using it gives `conformance macros are replaced by extension macros`. ## Declaring the names a macro introduces Peer and member roles state the names of the declarations they produce in a `names:` argument; an accessor role needs one when it generates `willSet` or `didSet`, and an extension role when it adds declarations inside the extension. The list may contain: - `named(x)` for a fixed name; - `overloaded` for the attached declaration's own name; - `prefixed(p)` and `suffixed(s)` for names derived from it; - `arbitrary` for names known only after expansion. The compiler holds the expansion to that list. A name outside it fails with `declaration name '…' is not covered by macro '…'`, and a peer macro at global scope may not use `arbitrary` at all. Listing names lets name lookup skip macros that cannot produce the name it is looking for, which keeps incremental builds cheaper. ## Rules the compiler enforces - A macro is declared **at file scope**; inside a type you get `macro '…' can only be declared at file scope`. - An accessor macro cannot go on a `let`: `cannot expand accessor macro on variable declared with 'let'`. - An extension macro cannot go on a local type: `local type cannot have attached extension macro`. - Only an extension macro declares a conformance. A member macro that lists `conformances:` is told which listed protocols are still missing and can add members that must live in the type itself, such as a required initializer. - At most one body macro may sit on a function, and the body as written must parse but is not type-checked before expansion. ## Choosing a role 1. A value computed from a literal or expression at the call site: **expression**. 2. New top-level or local declarations from a single call: **declaration**. 3. A companion to one declaration, such as an overload or a mock: **peer**. 4. Storage, initializers or constants inside a type: **member**, often paired with **extension** for the conformance. 5. Stored properties that should route through generated accessors: **accessor**, often applied to each property by a **memberAttribute** macro on the type. 6. Code that must wrap or supply a function's body: **body**. The SwiftUI and SwiftData material covers what specific framework macros generate; the roles above are the language rules every one of them obeys.
- Why must a peer or member macro list its names, and what happens when the expansion goes outside the list?The list lets name lookup skip macros that cannot produce the name it wants, so it does not expand everything in scope. A name outside the list fails the build with `declaration name 'fetchAvatarWithCompletion' is not covered by macro 'AddCompletionHandler'`. `arbitrary` covers any name but forces expansion during lookup, and a peer macro at global scope may not use it.
- Can one macro have more than one role?An attached macro can: write one `@attached` attribute per role, as the book's `@OptionSet` does with `member` and `extension, conformances: OptionSet`, and make the implementation type conform to each matching protocol. A freestanding macro cannot; two freestanding roles give `macro can only have a single freestanding role`.
- What can an extension macro add that a member macro cannot?A protocol conformance. Only an extension macro declares conformances, listed in `conformances:`. A member macro given `conformances:` receives the listed protocols the type does not yet conform to and can add the members that must live in the type itself, such as a required initializer or stored property, but it cannot declare the conformance.
- Attached macros are called with # in front of a declaration.
- One freestanding macro can declare both expression and declaration roles.
- A member macro can add a protocol conformance on its own.
- An accessor macro can be attached to a let constant.
- A peer macro needs no names: list to add a named function.
Assumes Swift 6.4; expression, declaration and every attached role except body shipped in Swift 5.9; the body role arrived in Swift 6.0 (SE-0415).