Macro to collate types

Hi there,

Is it possible to create a macro to collate types? I can't think how to achieve anything like this. For example:

struct Zoo {
    struct Cheetah { }

    struct Zebra { }

    struct Rhino { }

    func catalog() {
        let allAnimalTypes: [Any] = #CollatedTypes

I'm hoping the expanion of #CollatedTypes might look like this:

let allAnimalTypes: [Any] = [ Cheetah.self, Zebra.self, Rhino.self ] 

In my real-world scenario, I have lots of builder types spread over multiple source files with a manual array to ensure they each get instantiated. Errors are introduced if the array is not updated when adding new builder types or removing builder types.

Thanks for your help.

1 Like

Hmm… macros attached to nested types and stand-alone expression macros by design probably wouldn't have enough "state" to make this work.

I could see a macro attached to the Zoo struct itself working. At that point the catalog function would also be generated by the macro and the macro itself would aggregate the Collate types to build that definition.

Thank you, @vanvoorden, I'll try that. I'm not sure yet how to make that work across multiple source files, but I'll give it a go.

I wondered about the @Collate macro extending some dummy type with a computed property, but a) I don't think extension macros are allowed to extend other types, and b) Swift reflection doesn't give you access to computed properties.

The builders in the real-world example are used to generate data for an app. If I implemented this as a command line application, will a peer macro allow me to add arbitrary code at global scope? I could have a static array defined at global scope and @Collate could generate code to append the attached type to it.

Thanks again.