Swift and Object-C Interop, Simplest Possible Example

Start with a Single View App (Swift) in Xcode 9 Beta 6 called SwiftObjCInterop.


Swift Calls Objective-C

Create an Objective-C Class

Create an Objective-C class called ObjCObject

This will automatically give you the Bridging Header to call the Objective-C from Swift (that was easy!):

Select Create Bridging Header which will produce the file SwiftObjCInterop-Bridging-Header

Add a Method to ObjCObject

Add a method like this in your .m file

- (void) test {
    NSLog(@"Yes we are ObjCObject and we are testing");
}

and this in your .h

- (void) test;

Add ObjCObject to your Bridging Header

#import "ObjCObject.h"

Test Swift Calls Objective-C

Put this in your viewDidLoad:

ObjCObject().test()

Run the project. Now Swift calls Objective-C.


Objective-C Calls Swift

This is slightly trickier in an existing project, but in a new project there are no issues.

Include this in your ViewController.swift file:

@objc(testSwift)
func testSwift() {
    print("yes ViewController is printing")
}

For some reason, you need the @objC tag to be able to see your method from Objective-C.

Include this import in your .m file:

#import "SwiftObjCInterop-Swift.h"

And add this to your test method in your Objective-C class:

ViewController *vc = [[ViewController alloc] init];
[vc testSwift];

That's it.