How to call Objective-C code from Swift

devquora
devquora

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;
@end
In CustomObject.m
#import "CustomObject.h"
@implementation CustomObject 
- (void) someMethod {
    NSLog(@"SomeMethod Ran");
}
@end

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"
     println(instanceOfCustomObject.someProperty)
    instanceOfCustomObject.someMethod()

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?

    Swift is an advanced language for iOS development, known for its concise and expressive syntax. It enables fast-running software and is used for developing iOS and OS X applications, making it ideal f..

    Swift Interview Questions

    What is Dictionary in Swift?

    In Swift, key-value pairs allow for efficient data storage and retrieval, functioning similarly to hash tables in other programming languages. Accessing values is straightforward by using the correspo..

    Swift Interview Questions

    Explain Enum in Swift?

    In Swift, enums define a common type for a group of related values, enabling type-safe handling within your code. Essentially, an enum groups various related values under the same umbrella, facilitati..