Attached Member Macros for Boilerplate Reduction
Auto-generating init, CodingKeys or Equatable conformances with member macros.
Attached Member Macros for Boilerplate Reduction is a free Swift Academy lesson on CoddyKit. This is lesson 3 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, and your progress syncs across the web and the CoddyKit app. The Swift Academy course includes 4 lessons in total.
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()"]
}
}Generating init
Member macros can generate a custom initializer, replacing the memberwise init when needed.
// Macro expansion returns:
[
"init(name: String) { self.name = name; self.id = UUID() }"
]@Observable Macro Internals
Swift's built-in @Observable uses member macros to add observation infrastructure to your class.
@Observable
class Counter {
var count = 0
// macro adds: _$observationRegistrar, access(), withMutation()
}Reading the Decorated Type
Access the properties of the decorated type via the decl parameter to generate context-aware members.
if let structDecl = decl.as(StructDeclSyntax.self) {
let members = structDecl.memberBlock.members
// iterate to inspect stored properties
}Extracting Stored Properties
Filter member list for variable declarations with stored-property patterns to drive codegen.
let storedProps = members.compactMap { member -> VariableDeclSyntax? in
guard let varDecl = member.decl.as(VariableDeclSyntax.self),
varDecl.bindingSpecifier.tokenKind == .keyword(.var)
else { return nil }
return varDecl
}Generating Equatable from Members
A @AutoEquatable macro can generate == by comparing each stored property.
// Generated code:
static func == (lhs: User, rhs: User) -> Bool {
lhs.name == rhs.name && lhs.id == rhs.id
}Combining Member + Conformance Macros
Often you pair MemberMacro with ConformanceMacro to both add members and declare the protocol conformance.
struct AutoEquatableMacro: MemberMacro, ConformanceMacro { ... }Attribute Arguments
Your macro can accept arguments that customize the code it generates.
@Clamped(range: 0...100)
var score: Int = 50
// macro reads range from attribute node and generates clamping accessorsMacro Error Reporting
Throw MacroExpansionError or emit diagnostics when the macro is used incorrectly.
guard decl.is(StructDeclSyntax.self) else {
throw MacroError.message("@AddID can only be applied to structs")
}Build Performance
Because expansion is compile-time, member macros add zero runtime overhead and generated code is cacheable.
// All generated members are emitted as source code
// and compiled normally — no reflection at runtimeQuick Check
Which protocol must an attached member macro conform to?
Lesson Recap
Member macros (MemberMacro) generate stored properties, computed properties, and initializers for the type they decorate. Read the type's existing members to produce context-sensitive code. Combine with ConformanceMacro to also add protocol conformances.
Learn Swift with an AI tutor — free
Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.
- Courses
- 122
- Lessons
- 409
Frequently Asked Questions
Is the “Attached Member Macros for Boilerplate Reduction” lesson free?
Yes — any 3 lessons of the Swift Academy learning path, including “Attached Member Macros for Boilerplate Reduction”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Swift Academy course includes 4 lessons in total.
What will I learn in “Attached Member Macros for Boilerplate Reduction”?
Auto-generating init, CodingKeys or Equatable conformances with member macros. You practise Swift Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Swift Academy?
No prior experience is required. Swift Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 3 of 4.
How long does the “Attached Member Macros for Boilerplate Reduction” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Swift Academy lesson?
Yes. Every Swift Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
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