Handling macros errors
When we create a Swift macro, things obvious to us, as the macro developers, are not obvious to our macro users.
Our StructInit
macro is designed to function exclusively with structs, not classes. Therefore, we need to check whether the attached element is indeed a struct.
Inside the expansion()
function, we can perform a simple guard
statement and throw an error in case the attached declaration is not a struct:
guard let structDecl = declaration.as(StructDeclSyntax.self) else { throw StructInitError.onlyStructs }
In the preceding code, StructInitError
is an enum that conforms to Error
:
enum StructInitError: CustomStringConvertible, Error { case onlyStructs var description: String { switch self { case . onlyStructs: return...