Swift: Calling Swift code from Objective C

The topic came up over on irc about whether you could build Swift classes and call them from Objective-C. I headed over to “Using Swift with Cocoa and Objective-C” and the docs seemed to be clear that this was possible. So I created the following swift app. It’s not much of an app and I’ve got everything pretty much marked out with the @objc keyword.

import Foundation
@objc class TestClass : NSObject
{
    @objc func test() -> NSString
    {
        return "Generated by Swift"
    }
}

After a bunch of googlage, I found this q&a over at Stack Overflow, which helped me get through the remaining steps which were these. (I haven’t really had a lot of time to test them, so if you find any I could skip / tweak, let me know!)

1.  Select your target, and in Build Settings, edit your Packaging > Product Module Name > to your project name

2.  In your Objective-C class, import “<name>-Swift.h”, for example “Test-Swift.h”, matching all the bits before the hyphen to the name from step 1.

Compile and run.

I did not need to use the Objective-C bridging header and I ended up deleting it from my project (making sure to clear it out from my build settings as well.)

I’d like to know exactly how much “@objc”-ing is really necessary and whether the default project name is enough without step 1. That will, however, have to wait because it’s Friday, it’s late, and I just spent many hours getting my SpriteKit visualizer stuff updated for iOS 8, so I only had a little time for this.

One Comment

  • If your Swift class inherits from an ObjC class (such as NSObject), you don’t need to explicitly add “@objc” to the class or any of its method. Also, the bridging header is only required for when you’re calling ObjC code from Swift; calling Swift code from ObjC relies on Xcode’s generated “Module-Swift.h” header, as you pointed out