如何在Swift中导入现有的Objective C类 [英] How to import existing Objective C classes in Swift
问题描述
我曾经在XCode 6.0 DP中使用Swift一段时间,在我现有的项目中使用它。
我试图从我的ViewController.swift文件中访问MyModel.h(我现有的Objective C Model对象)。我想将
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
#importMyModel.h
导入我的Swift文件。
但是我找不到如何做到这一点。
#import "MyModel.h"
to my Swift file.
But I could not find how this can be done.
推荐答案
如果某人面临同样的问题,可以发布答案。
Posting the answer if it helps some one facing the same issue.
我发现在iOS Developer Library中提供了一个非常直接的解决方案。请参考以下链接:
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:
Apple Doc说:
Apple Doc says:
要在与
Swift代码相同的应用程序目标中导入一组Objective-C文件,您需要使用Objective-C桥接头将这些
文件公开给Swift。当您将
Swift文件添加到现有的Objective-C应用程序或将Objective-C文件添加到
现有的Swift应用程序时,Xcode可以创建此头文件。
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.
所以我创建了 MyApp-Bridging-Header.h
文件并添加了以下行:
So I created MyApp-Bridging-Header.h
file and just added the following line:
#import "MyModel.h"
现在它允许我在我的 ViewController.swift
中使用该模型,如下所示:
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")
对于任何人正试图解决这个问题。如果必须从头开始创建桥接文件,还必须在Build Settings> Swift Compiler> Objective-C Bridging Header中指定它的路径。
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.
这篇关于如何在Swift中导入现有的Objective C类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!