How would I wrap C++ source code to be used in Swift? I'm not even sure how to get started. What is the best approach? Would I necessarily have to compile the C++ code into a static library?
ShinehahGnolaum wrote:
How would I wrap C++ source code to be used in Swift? I'm not even sure how to get started. What is the best approach? Would I necessarily have to compile the C++ code into a static library?
You can't do this directly.
Most of the advice you will find says to use C as a lowest-common denominator. I don't like that approach because Swift doesn't even handle C that well.
Here is what I do:
Wrap all the C++ code you want to use into Objective-C++ classes. You probably don't need to use every method, so try to limit the busywork whenever you can. Each Objective-C++ class should inherit from NSObject or some other Objective-C++ class. In the public interface, provide access to the properties and methods you need - but no C++ data of any kind. For each Objective-C++ header "Foo.h", create a counterpart named "FooPrivate.h". Put all your C++ data into "FooPrivate.h". Your Objective-C++ source files can import any and all "Private.h" files. (Maybe "++" would be a better term instead of "Private".)
Wrap that up in a Framework and export to Swift. Maybe add a Swift header and tweak it until it looks the way you want in Swift. Write a good set of unit tests in Swift.