Friday, 20 March 2015

Using Swift code in Objective-C

I had a right pain getting this to work, once again Apple seem to have created something bafflingly unintuitive. I found these instructions elsewhere and have copied them virtually unmodified:

The file name of the generated header is "ModuleName-Swift.h". The ModuleName here is the Product Module Name, here's how to get to it:

1. Select your project in Project Navigator, then select project name under the word Project, so it’ll show you your project settings.

2. Select Build Settings tab on top, and find the Packaging section (you can type its name in the search bar). Here’s Product Module Name. If its value is the name of your project, then let it be, but you may want to change it if the value is a little bit different from the name of the project. I’d recommend not to use spaces or any other non-alphanumeric characters, here’s why:
If it has spaces or any other non-alphanumeric characters, they’ll become replaced with underscores (_) in the header file name. Also, Apple tells us that “if the name begins with a number, the first number is replaced with an underscore”.

Now build the project. Make sure that you have no build errors at all — Xcode must say “Build succeeded”. If it happened, then Xcode have probably generated the header. It won't appear in your project in Xcode or in its folder. It’s generated into a temporary build directory. Try to import it into the file where you want to use your Swift code by typing

#import "ModuleName-Swift.h"

In which ModuleName is your Product Module Name. You have to type it blindly, there’s no autocompletion here. So type this and build your project again. If you got “Build succeeded” message, then you’re done and Swift code is successfully integrated into Objective-C. It even autocompletes your class names, methods and variables written in Swift.

No comments:

Post a Comment

Comments are moderated, so you'll have to wait a little bit before they appear!