Swift: How to PROPERLY combine Objective C and Swift in a single project! (Part 2 of a series)

After some handholding help by Lily Ballard, I managed to get everything working for some complex cross-platform code. Here are the lessons along the way.

There’s one entirely essential lesson, which is this:

It’s not enough to just create a bridging header. If Xcode didn’t offer to build it on  your behalf, you must manually add it to your build settings.  Select your PROJECT > Build Settings and search for “bridging”. Set your Objective-C Bridging Header to your project-relative header file name. The path works the same way your Info.plist does.

And now for the more amusing bits:

Feel free to drop compatibility aliases and replace them with #defines. Old-style ObjC-aliases won’t kill you with ObjC/Swift but they won’t exactly help you either. More relevantly, never listen to drunk Frenchmen when coding late on Saturday night.

If you’re doing cross-platform development, make sure you import Foundation in your Objective C code before you do absolutely anything else. A lot of my code is cross-platform and the TargetConditionals.h file won’t get added otherwise. Without this all your #if TARGET_OS_IPHONE stuff won’t work right. Which was fun, fun, fun. (Not.) This particular step isn’t entirely essential if you’re not doing cross-platform development but it won’t hurt.

Lessee, what else? Don’t forget to add #imports as if you were a client .h or .m file in the bridging header, and…that’s about it actually. Oh, and auto-complete really stinks for this, so keep your normal .h file open for reference.

My original write-up on this topic can be found here.

(Thanks Lily and Remy!)

3 Comments

  • […] JUST POSTED AN UPDATE ABOUT COMPLEX PROJECTS. PLEASE READ THAT TOO! […]

  • If Xcode didn’t offer to build a bridging header on your behalf, you may have problems with library loading. Make sure you convert to a mixed-language project via New/File/OSX/Source/Cocoa Class, which should give you the “Hey! It looks like you’re creating a mix and match project” dialog.

    • To make Xcode offer to build a bridging header you need to set the module identifier first (Build settings -> Kernel Module). After that, if the bridging header’s path is empty in build settings when you import some .m file Xcode will finally offer to create the bridging-header

      (And watch out using white spaces in the name)