Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoking swift in objective-C++ (.mm file)

Can one invoke Swift code in a Objective-C++ (.mm) file? Are there any simple workarounds if not?

I have a Xcode project that is a mix of Swift, Objective-C and C++. I have no problem going from Objective-C to Swift with the -Bridging-Header.h or from Swift to Objective-C with the -Swift.h.

I do however have a .mm file which is Objective-C++. When I try to #import "[ProductName]-Swift.h" it throws many compile errors in the -Swift.h file such as:

Cannot find protocol declaration for 'NSApplicationDelegate', did you mean 'NSConnectionDelegate'?

No type protocol named 'NSTableViewDataSource'

etc...

I have looked into several other similar questions such as Can I mix Swift with C++? Like the Objective - C .mm files but it does not seem to give me an explicit answer or a solution.

As I see it, my current workaround is to create a wrapper object in Objective-C that uses the Swift code and then import that into the Objective-C++ code.

like image 506
Wesley McCloy Avatar asked Oct 14 '15 23:10

Wesley McCloy


1 Answers

I just succeeded in compiling a .mm file invoking swift by adding -fcxx-modules flag. The <Module>-Swift.h file generated by Xcode includes @import and checks for modules support. Found out the flag from this answer: https://stackoverflow.com/a/20708695/2570853.

enter image description here

like image 178
cahn Avatar answered Oct 15 '22 09:10

cahn