Can a macro generated initializer keep the memberwise initializer?

The Swift compiler synthesizes a memberwise initializer for struct declarations automatically. If you write your own initializer, it overlaps the synthesized one. A solution to have both your initializer and the synthesized memberwise one is to write your initializer on an extension for the struct.

Is it possible to achieve this behavior with a macro? Is it possible for a macro to generate an initializer without overlapping the synthesized memberwise initializer?

Just generating an initializer with a macro does the same thing as typing it would do: the memberwise initializer is not synthesized anymore. At the same time "Macro expansion cannot introduce extension", so I can't do the solution I've talked about on the first paragraph.

I'm not sure what solutions to try next. Any suggestions? :slight_smile:

1 Like

It's correct that macros in current form can't create an extension, and writing your own initializer would prevent the compiler from automatically synthesizing a memberwise one for your struct.

Holly has added a proposal to generalize the conformance macro role to an extension macro role. If this is accepted and implemented, you could use an extension macro to add your custom initializer as an extension of your struct, without interfering with the memberwise initializer synthesized by Swift.

Hope this helps! :heart:

3 Likes

Wow! Thank you for your very quick answer that is both to the point and suggests a possible future alternative to make it work.

I'll keep an eye on that proposal for sure!

1 Like