var modelContext @Query var items: [Item] ... } // Generated struct ContentView_Content: View { @Environment(\.modelContext) var modelContext let items: [Item] ... } Why Can't We Have Nice Macros for #Preview? 5 / 21
produce an expression or declaration attached macros (@Observable) attach to existing declarations and augments Why Can't We Have Nice Macros for #Preview? 10 / 21
produce an expression or declaration attached macros (@Observable) attach to existing declarations and augments peer : adds a declaration alongside member : adds members (properties or methods) ... Why Can't We Have Nice Macros for #Preview? 11 / 21
macros arguments 2nd phase Expands macros & type-checks them When a macro expansion is encountered in the source code, its expansion occurs in two phases. The first phase is the type-check phase, where the arguments to the macro are type-checked against the parameters of the named macro, and the result type of the named macro is checked against the context in which the macro expansion occurs. … The second phase is the macro expansion phase, during which the syntax of the macro arguments is provided to the macro de nition. fi ’ Why Can't We Have Nice Macros for #Preview? 14 / 21
names: named(access)) macro Observable() • A part of @Observable • Via conformances extension Observable { func foo() {} } @Observable class Model {} #Preview { Model().foo() // ✅ Model().access(keyPath: \.self) // 🛑 } Why Can't We Have Nice Macros for #Preview? 16 / 21
names: named(access)) macro Observable() • A part of @Observable extension Observable { func foo() {} } • Via conformances access @Observable class Model {} • A product of @Observable • Via names #Preview { Model().foo() // ✅ Model().access(keyPath: \.self) // 🛑 } Why Can't We Have Nice Macros for #Preview? 17 / 21
address these issues, a name introduced by a macro expansion is not visible within macro arguments for macros the same scope as the macro expansion or any of its enclosing scopes. [from SE-0389] https://github.com/swiftlang/swift-evolution/blob/main/proposals/0389attached-macros.md#visibility-of-names-used-and-introduced-by-macros Why Can't We Have Nice Macros for #Preview? 18 / 21
Expansion could break its own argument's type-check 2. Order dependency • Expansion order would change code meaning • Swift doesn t prefer order dependencies 3. Expansion cost • Macros should be expanded only once https://github.com/swiftlang/swift-evolution/blob/main/proposals/0389attached-macros.md#visibility-of-names-used-and-introduced-by-macros ’ Why Can't We Have Nice Macros for #Preview? 19 / 21