0Pricing
Swift Academy · Lesson

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

  1. Macro Roles: Freestanding vs Attached
  2. Writing a Freestanding Expression Macro
  3. Attached Member Macros for Boilerplate Reduction
  4. Testing and Debugging Macros
← Back to Swift Academy