Wednesday, September 30, 2020

How To Invoke Swift code from Objective C code

I wasted a couple of hours trying to do exactly this. The lack of clear documentation didn't help either. I decided to write small post about this so that others do not have to waste their time digging through the documentation.

How do you invoke Swift code from Objective C code?

Swift class either need to be derived from NSObject or they need to be @objc attribute. Let's look at a simple swift class that we want to invoke from Objective C

When you add the Swift class to the Objective C project, XCode will ask whether you want to generate the "Bridging Header", just say yes. This header is useful when you want to invoke Objective C code from Swift code. But we are interested in doing the opposite, i.e. invoke Swift code from Objective C code.

Next we need to head to XCode -> Project Properties -> Target -> Build Settings, search for "Generated Interface". You should see a single entry called "Objective-C Generated Interface Header Name". You need to make a note of the generated header file name, it follows the format "<Product Module Name>-Swift.h"

This is the name of the header file that we need to include in our Objective C code to invoke the Swift code. This header file is auto-generated by XCode.

In the Build Settings search for "Bridging Header". You should see an entry called "Objective-C Bridging Header". This setting points to the path of the Bridging Header generated by XCode earlier. The value here should have been populated by XCode automatically. 

We also need to set the value of "Swift Language Version" Build Setting. Search for "Language Version" and set the value.

Now that the Build Settings are out of the way, here is the sample Objective C code which invokes the Swift class we defined above.

Please note that you can only include the "<Product Module Name>-Swift.h" in the .m or .mm files. To use the Swift class in .h file, just forward declare it using @MySwiftClass.

Thats about all there is to invoke Swift code from Objective C, we do not need to change any other Build Settings. If the documentation was clear enough, I would not have to write this post!
Have some Fun!