Exposing Swift Implementations to Objective-C | humancode.us

Interesting writeup here by Dave Rahardja talking about including header files with Swift code for better Objective-C interop.

source

Many large projects contain a mix of Objective-C and Swift code. So, it’s often useful for libraries to expose both Objective-C and Swift interfaces to a common implementation, so the library can be used everywhere in a project.

One customary way to do this is to implement your library in pure Objective-C. As long as your library is packaged as a module (framework), you can easily use the code from both the Objective-C and Swift parts of your project. The downside of doing this is that your interface tends to not feel very Swifty”. As more and more of your code moves to Swift, you will find yourself wanting a more idiomatic Swift interface that may be impossible to achieve with pure Objective-C headers.

Another step one could take would be to create a Swift overlay to your otherwise pure Objective-C library. You mark your Objective-C symbols NS_REFINED_FOR_SWIFT and provide an alternative API in Swift that provides a Swift interface, but uses your Objective-C implementations under the hood. You can go a long way with this technique, but you may eventually find that optimizing for the Swift user of your library is more valuable than prioritizing the Objective-C user.

That brings us to what this post addresses: how you can write your library in Swift, yet still expose an Objective-C header that maps Objective-C users of your library directly to the Swift implementation, with no manual bridging. I hope that the value of this utility is apparent at this point.



Date
May 19, 2024