Swift Macro inheritance with nested class

Hi,

I'm trying to make a macro like this:

class ParentClass {

   @MyMacro
   class NestedClass {
   }

}

When the macro expands I want to get this:

class ParentClass {

   class NestedClass: Equatable, CustomStringConvertible {
   }

}

From what I have seen we can create a macro to create an extension.
But in the case of a nested class it does not work.

class ParentClass {

   class NestedClass {
   }

  // ❌ error: Declaration is only valid at file scope
  extension SubClass: Equatable, CustomStringConvertible {}
}

I just want to change the inheritance of the class on which the macro applies, not to create an extension.
Is it possible to do this?

Thanks,
Tof

According to the extension macro proposal, this should be possible. See extension macro application.

Can you share the code where you declare the macro?

I saw something similar… it might be the same problem in the task that was filed.

Does your code compile correctly when the macro is expanding through the compiler? Is the bug happening just when expanding or inlining the macro through Xcode before compiling?

For the most part macros are designed to be strictly additive… you can add new code… but not edit or remove code. There are a few exceptions to this rule… but for your specific use-case it sounds like you should declare an extension on SubClass with the protocols you want to adopt.

1 Like