'Calling swift function from objective-c++

I'm having issues with calling swift methods & using swift classes inside objective-c++ code. I have following class in swift:

@objc class MetalRenderer : NSObject
{
    // implementation
    ...
}

Then I have header file in which I have forward declaration @class MetalRenderer; and in source (.mm) file I include "Project-Swift.h" file and instantiate swift class and call methods on that class, no problem. However, when I try to make my class conform to MTKViewDelegate protocol code doesn't work anymore. This is what I have in swift:

@objc class MetalRenderer : NSObject, MTKViewDelegate
{
    // implementation
    ...

    func mtkView(_ view: MTKView, drawableSizeWillChange size: CGSize) {
        //...
    }

    func draw(in view: MTKView) {
        //...
    }
}

Same header file & including same "Project-Swift.h" file in .mm. However now the .mm fails to compile, with

No type or protocol named 'MTKViewDelegate'

I'm C++ developer with little understanding of Obj-C/Obj-C++/Swift. I understand that there is problem in "-Swift.h" file, which doesn't know the MTKViewDelegate protocol. The same file includes both Metal and MetalKit frameworks which has definition of that protocols. Those imports are however surrounded by preprocessor guards for some modules. I've found some posts about people having similar issues and the proposed solutions are to get rid of some include cyclic references, which are not present in my case (I guess) or to use swift code in Objective-C and not Objective-C++. I wrapped my code in Objective-C class and it works again, but I don't understand why I can't call it directly from Objective-C++, because the code is basically the same & I'm not satisfied with that I have to provide unnecessary indirection of wrapping that code. My question is, is it possible to directly call swift class methods from objective-c++, why it doesn't work (probably because of those modules, but what are they, how they work?)?



Solution 1:[1]

Those imports are however surrounded by preprocessor guards for some modules.

Looks like you have already answered yours question: MetalKit framework isn't included.

You can just declare MTKViewDelegate protocol prototype if importing whole framework causes troubles

Solution 2:[2]

Import MetalKit at the top of your .mm file:

#import <MetalKit/MetalKit.h>
#import "Project-Swift.h"

I was having the exact same problem and this fixed it for me.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Cy-4AH
Solution 2 AbePralle