Applying a macro with another macro

I'd like to create a macro that generates some properties and also applies another macro. Essentially an "extension" of the existing macro.

Is this possible?

@FooObservable
final class User {
    let id: Int
    var name: String
}

Which would generate a type that has the @Observable macro applied in addition to having some external functions that could then depend on the type being Observable.

Hi there!

I'm not sure if I fully understood your case, but would this example be the thing you want to achieve?

Here you can find the most up-to-date version of this example, which is compatible with the latest environment. The following code is part of an effort to incorporate Doug’s macro examples into swift-syntax/Examples.

I'm basically looking to compose one macro with some additional features.

For example, @FooObservable would be a macro that does two things:

  1. Applies @Observable to the type.
  2. Adds a function func foo() to the type.

The catch is - func foo() will have its implementation dependent on the type being Observable, so it wouldn't make sense to be an entirely separate macro.

e.g.

@FooObservable
class User {
    let id: Int?
    let name: String
}

// would generate...

@Observable
class User {
    let id: Int?
    let name: String

    func foo() {
        print("Hello from Foo!")
    }
}

Hi, for your information there is a dedicated category to post about macros, you might find more help there, it's in Development→ macro.

1 Like

Did you figure out how to accomplish this?

1 Like

I don't think this is possible at this time. There is a memberAttribute macro but no attribute macro. I feel like this is kind of a hole, but I think it's done purposefully.

1 Like