cs1

I am taking this first dive into the ocean of Blogging.

Today we will learn about using objective-c classes in Swift (also known as bridging ) in iOS. Now you will wonder what is Bridge? Bridge means interconnection between two languages. So How do we implement objective-c classes in Swift?

Step 1: Add Objective-C Implementation — .m

Add a .m file to your class, and name it CustomObject.m

Step 2: Add Bridging Header

When adding your .m file, you’ll likely be hit with a prompt that looks like this:

nakLZ

Click YES !

If you did not see the prompt, or accidentally deleted your bridging header, add a new .h file to your project and name it <#YourProjectName#>-Bridging-Header.h

In some situations, particularly when working with ObjC frameworks, you don’t add an Objective-C class explicitly and Xcode can’t find the linker. In this case, create your .h file named as mentioned above, then make sure you link its path in your target’s project settings like so:

8LiwF

Note

It’s best practice to link your project using the $(SRCROOT) macro so that if you move your project, or work on it with others using a remote repo, it will still work. $(SRCROOT) can be thought of as the directory that contains your .xcodeproj file. It might look like this:

$(SRCROOT)/Folder/Folder/<#YourProjectName#>-Bridging-Header.h

Step 3: Add Objective-C Header — .h

Add another .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: Add Class to Bridging-Header

In YourProject-Bridging-Header.h:

#import "CustomObject.h"

Step 6: Use your Object

In SomeSwiftFile.swift:

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

No need to import explicitly, that’s what the bridging header is for.

So now you can dive into Swift development without worrying about if swift will support this library or not. Do drop me your suggestions how can I improvise in blogging :)

Bridging in Swift

Tushar Patel

It takes pleasure to introduce myself, I am Tushar Patel, well I am not Geek nor I am Super Techie but I am passionate about coding & learning new things and exploring new dimensions, and I love to make new friends across the globe. You can contact me on http://tinyurl.com/qz5ze3t

Category: Uncategorized
1
1186 views

1 comment

Comments are closed.