How to call Objective-C code from Swift


Posted On: Feb 22, 2018


Follow the following steps:

Step 1: Add Objective-C Implementation --.m: First of all, add a .m file to the class and then name it CustomObject.m.

Step 2: Add Bridging Header: At the time of adding your .m file, you receive a prompt with three options of YES, NO and cancel. You need to select YES

Step 3: Add Objective-C Header --.h: After that Add one more .h file and name it CustomObject.h.

Step 4: Build your Objective-C Class

In CustomObject.h

#import <Foundation/Foundation.h>
@interface CustomObject : NSObject
@property (strong, nonatomic) id someProperty;
- (void) someMethod;
In CustomObject.m
#import "CustomObject.h"
@implementation CustomObject 
- (void) someMethod {
    NSLog(@"SomeMethod Ran");

Step 5: The next step is to add Class to Bridging-Header

In YourProject-Bridging-Header.h

#import "CustomObject.h"

Step 6: At last, use your Object

In SomeSwiftFile.swift:

     var instanceOfCustomObject: CustomObject = CustomObject()
     instanceOfCustomObject.someProperty = "Hello World"

In the bridging header, there is no need to import explicitly.

    Related Questions

    Please Login or Register to leave a response.

    Related Questions

    Swift Interview Questions

    What is IOS Swift?

    iOS swift is an intuitive and stalwart language for the iOS. It is joyful to deal with the writing stuff in Swift. It is very advanced and its syntax is also concise and expressive too...

    Swift Interview Questions

    What is Dictionary in Swift?

    It enables you to store the key-value pairs and access the value by providing the key.It is similar to that of the hash..

    Swift Interview Questions

    Explain Enum in Swift?

    Basically, it is a type that contains a group of various related values under the same umbrella...