Swift: Combining ObjC and Swift in one project

JUST POSTED AN UPDATE ABOUT COMPLEX PROJECTS. PLEASE READ THAT TOO!

When you add an Objective-C class to an otherwise-swift project, Xcode invites you to create a bridging header file. This files enables your swift code to access your ObjC classes. I’ve had success with this, but only when I’ve built new ObjC classes from scratch. My complex cross-platform Constraint Pack was too much for it to handle. Here’s what I did to successfully make this work on a trivial case.

  • Created a TestClass.[hm] pair.
  • Agreed to build a bridging header file
  • Built out the test class to a really minimal implementation: one method, – (void) testAction, which logs hello

@implementation TestClass
– (void) testAction
{
NSLog(@”here”);
}
@end

  • Added the full headers to the bridging file:

@import UIKit;
@import Foundation;

@interface TestClass : NSObject
– (void) testAction;
@end

  • Tested the class from my swift source

let foo : TestClass = TestClass()
NSLog(“\(foo)”)
foo.testAction()

And everything works as promised. But for very small values of “combining objc/swift”…

5 Comments