Applying Macros
Use macros to generate repetitive code at compile time.
Overview
Swift macros help you avoid writing repetitive code in Swift by generating that part of your source code at compile time. Calling a macro is always additive: The macro adds new code alongside the code that you wrote, but never modifies or deletes code that’s already part of your project.
Many libraries provide macros, including the Swift standard library and many frameworks. You can also write your own macros.
Because macros generate Swift code, you use the same tools for development and debugging, regardless of whether your code uses macros.
[Image]
Call a Macro
The syntax you use to call a macro varies slightly, depending on whether you attach the macro to a declaration.
To attach a macro to a declaration, write an at sign (@) before the macro’s name and write any macro arguments after its name. This syntax is the same as writing an attribute. For example:
@Observable
public final class MyObject {
public var someProperty: String = ""
public var someOtherProperty: Int = 0
fileprivate var somePrivateProperty: Int = 1
}A macro that’s attached to a declaration generates code and adds that code to the declaration. For example, the Observable() macro in the code above adds additional members to the MyObject class so it implements the Observable protocol, and marks MyObject as conforming to Observable.
To call a macro without attaching it to a declaration, write a number sign (#) before the macro’s name and write any macro arguments after its name. This syntax is the same as #if and other compile-time operations. For example:
let messagePredicate = #Predicate<Message> { message in
message.recipient == "John Appleseed"
}A macro that isn’t attached to a declaration generates code and adds that code in the location where where you call the macro. For example, the Predicate macro in the code above creates an instance of the Predicate structure.
For more information, see Macros in The Swift Programming Language.
Inspect an Expanded Macro
When you build your project, Swift reads your code and finds the places where you call a macro. Swift then calls the implementation of each macro, to expand the code. Finally, Swift builds your project as usual, including the generated code.
To view the code that a macro generated, click on the code where you call the macro in Xcode, then choose Editor > Expand Macro. You can read the expanded code to help you understand details about the macro’s behavior, and you can use the expanded code to help you debug code that uses macros. For example, you can set breakpoints inside code generated by a macro.