Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import existing Objective C classes in Swift

Tags:

ios

swift

I had been messing around with Swift for a while in XCode 6.0 DP to use it in my existing project. I am trying to access MyModel.h(My existing Objective C Model object) from my ViewController.swift file. I wanted to import

#import "MyModel.h" to my Swift file. But I could not find how this can be done.

like image 274
shah1988 Avatar asked Jun 04 '14 09:06

shah1988


People also ask

Can you mix Objective-C and Swift?

Can I mix them in the same class? Yes! Just like you can extend classes in ObjC, you can extend classes with Swift as well. You can write a Swift extension for an ObjC class and it works just fine.

How can Swift and Objective-C be used in the same project?

To access and use swift classes or libraries in objective-c files start with an objective-c project that already contains some files. Add a new Swift file to the project. In the menu select File>New>File… then select Swift File, instead of Cocoa Touch Class. Name the file and hit create.

Can I use Swift library in Objective-C?

The Swift library cannot be directly called from Objective-C, since it is missing the required annotations in the code, and in many cases, modules do not inherit from NSObject, rather they use the native Swift data types.


1 Answers

Posting the answer if it helps some one facing the same issue.

I found that a pretty straight forward solution for How to do this is given in the iOS Developer Library. Please refer to the following link:

https://developer.apple.com/library/content/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html#//apple_ref/doc/uid/TP40014216-CH10-XID_75

Apple Doc says:

To import a set of Objective-C files in the same app target as your Swift code, you rely on an Objective-C bridging header to expose those files to Swift. Xcode offers to create this header file when you add a Swift file to an existing Objective-C app, or an Objective-C file to an existing Swift app.

So I created MyApp-Bridging-Header.h file and just added the following line:

#import "MyModel.h" 

Now it lets me use the model in my ViewController.swift as follows:

var myModel = MyModel() myModel.name = "My name" myModel.dobString = "11 March,2013" println ("my model values: Name: \myModel.name and dob: \myModel.dobString") 

FYI to anyone who is trying to figure this out. If you have to create the bridging file from scratch, you also have to specify a path to it in Build Settings > Swift Compiler > Objective-C Bridging Header.

like image 128
shah1988 Avatar answered Nov 05 '22 02:11

shah1988