Attached Member Macros for Boilerplate Reduction
Auto-generating init, CodingKeys or Equatable conformances with member macros.
Member Macro Overview
An attached member macro generates new members (properties, methods, inits) directly on the decorated type.
@AddID
struct User { var name: String }
// After expansion:
// struct User { var name: String; var id = UUID() }Conforming to MemberMacro
Implement MemberMacro and return an array of DeclSyntax representing the new members.
import SwiftSyntaxMacros
struct AddIDMacro: MemberMacro {
static func expansion(
of node: AttributeSyntax,
providingMembersOf decl: some DeclGroupSyntax,
in context: some MacroExpansionContext
) throws -> [DeclSyntax] {
return ["var id = UUID()"]
}
}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