Home IOS Development ios – Swift ExtensionMacro – Stack Overflow

ios – Swift ExtensionMacro – Stack Overflow

ios – Swift ExtensionMacro – Stack Overflow


I’m making an attempt to create a macro to help in testing on a manufacturing app and have been making an attempt a good few various things. Extra element:

Desired End result:

Within the venture we’ve got a variety of protocols, so given the beneath:

protocol Foo {
    var bar: Bool { get }
    func fooBar() -> Bool

We wish to create a @Testable that will we might use like so:

closing class FooSpy: Foo { }

This class could be outlined within the Testing bundle and we might count on the macro to increase into:

closing class FooSpy: Foo {

    var bar: Bool

    var fooBarExpectation = XCTestExpectation()
    var fooBarToReturn: Bool = false
    func fooBar() -> Bool {
        return fooBarToReturn



I’ve managed to create a PeerMacro that does the above by setting the protocol as @Testable. The difficulty is that the macro expands in place the place the protocol is and as such numerous testing associated code does not compile on account of lack of imports and so on.

I then went on to try to make an ExtensionMacro in order that I might mark the Take a look at class as @Testable which is contained in the check goal and thus has the required imports. The difficulty is, that with this strategy I do not appear to get entry to the Protocols conformance necessities. Code beneath

public struct Testable: ExtensionMacro {
    personal static let extractor = Extractor()

    public static func enlargement(of node: SwiftSyntax.AttributeSyntax, 
                                 attachedTo declaration: some SwiftSyntax.DeclGroupSyntax,
                                 providingExtensionsOf kind: some SwiftSyntax.TypeSyntaxProtocol,
                                 conformingTo protocols: [SwiftSyntax.TypeSyntax],
                                 in context: some SwiftSyntaxMacros.MacroExpansionContext) throws -> [SwiftSyntax.ExtensionDeclSyntax] {
// Right here I am making an attempt to get the protocol particulars (extractor beneath):
let protocolDeclaration = strive extractor.extractProtocolDeclaration(from: declaration)


struct Extractor {
  func extractClassDeclaration(
    from declaration: DeclGroupSyntax
  ) throws -> ProtocolDeclSyntax {

    guard let protocolDeclaration = declaration.as(ProtocolDeclSyntax) else {
        throw TestableMacroError.invalidProtocol

    return protocolDeclaration

The plain subject is that with the ExtensionMacro, the declaration is not the identical as when it is a PeerMacro so this code does not work.

How can I (if i even can) get the protocol particulars from a DeclGroupSyntax?



Please enter your comment!
Please enter your name here