How to import existing Objective-C classes into Swift

I messed 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) from my ViewController.swift file. I wanted to import

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

+43
ios swift
Jun 04 '14 at 9:59
source share
3 answers

Posting an answer if it helps someone in solving the same problem.

I found that a fairly direct solution to 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 into the same target application as your Swift, you rely on the Objective-C bridge header to make the files in Swift. Xcode suggests creating this header file when you add a Quick file to an existing Objective-C application or an Objective-C file for an existing Swift application.

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

 #import "MyModel.h" 

Now it allows me to 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 trying to figure it out. If you need to create a bridge file from scratch, you must also specify the path to it in the build settings> Swift Compiler> Objective-C Bridging Header.

+60
Jun 04 '14 at 10:03
source share

In Document for quick programming . There is no import operation.

enter image description here

+14
Jun 04 '14 at 10:01
source share

To import into a Swift application or into an Objective-C application that creates a mixed language application, you need to create a bridge header, which you can call Apple Docs

It says that

Objective-C and Swift files can coexist in the same project, regardless of whether the project was originally an Objective-C or Swift project. You can simply add another language file directly to an existing project. This natural workflow makes creating targeted applications for applications and applications in different languages ​​as easy as creating an application or framework written in one language.

To import a set of Objective-C files in the same target application as your Swift code, you rely on the Objective-C bridge header to output these files to Swift. Xcode suggests creating this header file when adding a Swift file to an existing Objective-C application or an Objective-C file to an existing Swift application.

EDIT: I created the code for your help, you can find it here

+5
Sep 09 '14 at 10:02
source share



All Articles