Writing boilerplate macros

The following code has a pattern that repeats:

class State {
    func handle (event: Play) -> State {
        fatalError ("\(type (of:self)) \(#function) \(event)")
    }
    
    func handle (event: Pause) -> State {
        fatalError ("\(type (of:self)) \(#function) \(event)")
    }
    
    func handle (event: Stop) -> State {
        fatalError ("\(type (of:self)) \(#function) \(event)")
    }
}

In C++, I can use this macro:

#define ___Event_Handler(__Event) \
       func handle (event: __Event) -> State { \
            fatalError ("\(type (of:self)) \(#function) \(event)") \
       }

to reduce the boilerplate in class State to this:

class State {
     ___Event_Handler (Play)
     ___Event_Handler (Pause)
     ___Event_Handler (Stop)
}

How do I achieve this using macros in Swift?

Could anyone provide a simple example that will benefit learners? :slight_smile:

Thank you

You can write an attached member macro that generates these functions and attach it to the State class.

But what I would consider first, is to add a PlaybackAction protocol and make Play, Pause and Stop conform to it. Then you don’t even need a macro because you can just write

func handle (event: any PlaybackAction) -> State {
  fatalError ("\(type (of:self)) \(#function) \(event)")
}
2 Likes