Using Objective-C Code in Swift

Photo by Nikhil Mitra on Unsplash

Prerequisites:

  • Be able to create a basic iOS single view application (Guide HERE)

Terminology

Bridging: The use of a header file to enable Objective-C code to be used in a Swift codebase

A demonstration in a simple project

Create a single view project with a button centred

This guide assumes that the reader can create a simple project, and instead of creating a label in the middle of the view put a button there, and add the action to your view controller.

Add a simple image to the project

We can add resources by dragging and dropping items into the project. You should drag + drop any JPEG image into the project to use as a background for the button

Add a TapGesture

Yes: There are other ways to make a button have an action, but in this case we will use a UITapGestureRecognizer that allows us to detect the use of the button:

let tapGesture = UITapGestureRecognizer(target: self, action: #selector(buttonTapped))
myButton.addGestureRecognizer(tapGesture)
@objc func buttonTapped() {
MyObjcClass().printit("Print ME")
}

Add an Objective-C class

We can add a Cocoa Touch class, and specify that we want the language to be Objective-C.

Add the Class to the Bridging Header

We need to add our class to objcswift-Bridging-Header.h, and it adds the following line:

Adding the Class to the Objective-C code

We then need to add the following signature to the interface (MyObjcClass.h):

- (void) printit:(NSString *)message;
- (void) printit:(NSString *)message {
NSLog(@"%@", message);
}

The result

When we run the application, when we click the button — it prints to the console!!! Woot!

Conclusion:

Objective-C is a great language. You might not choose to create your project in that language, but might need to bridge to Swift in order to not rewrite all of that (tested) code. It makes sense that bridging between the two languages is easy, and this guide helps you to be able to do just that.

Extend your knowledge

  • Apple have a guide about importing Objective-C into Swift HERE

The Twitter contact:

Any questions? You can get in touch with me here

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store