Macro Roles: Freestanding vs Attached
Understanding #expression macros, @attached peer/member/accessor macro roles.
What Are Swift Macros?
Swift macros expand source code at compile time, generating boilerplate automatically without runtime overhead.
// Macros are invoked with # (freestanding) or @ (attached)
#warning("Fix this later")
@Observable class Counter { var count = 0 }Freestanding Expression Macros
Freestanding expression macros start with # and produce a value or perform a side-effect.
// #stringify expands to a tuple of the value and its source string
let (val, src) = #stringify(1 + 2)
print(val, src) // 3, "1 + 2"All lessons in this course
- Macro Roles: Freestanding vs Attached
- Writing a Freestanding Expression Macro
- Attached Member Macros for Boilerplate Reduction
- Testing and Debugging Macros