在Swift中,如何调用Objective-C代码?

苹果提到它们可以共存于一个应用程序中,但这是否意味着人们可以在技术上重用Objective-C中创建的旧类,同时在Swift中构建新类?


当前回答

Create a .h file from NewFile -> Source -> header file Then save the name of file Your_Target_Name-Bridging-Header.h People here gets common mistake by taking their project name but it should be the Project's Target's name if in case both are different, generally they are same. Then in build settings search for Objective-C Bridging Header flag and put the address of your newly created bridging file, you can do it right click on the file -> show in finder -> drag the file in the text area then the address will be populated. Using #import Your_Objective-C_file.h In the swift file you can access the ObjC file but in swift language only.

其他回答

引用自文档:

Any Objective-C framework (or C library) that’s accessible as a module can be imported directly into Swift. This includes all of the Objective-C system frameworks—such as Foundation, UIKit, and SpriteKit—as well as common C libraries supplied with the system. For example, to import Foundation, simply add this import statement to the top of the Swift file you’re working in: import Foundation This import makes all of the Foundation APIs—including NSDate, NSURL, NSMutableData, and all of their methods, properties, and categories—directly available in Swift.

登录的答案工作良好,除了在最新的Swift 5,它给出了一些编译器错误。以下是针对Swift 5开发人员的修复。

斯威夫特5

import Foundation

class MySwiftObject : NSObject {

    var someProperty: AnyObject = "Some Initializer Val" as AnyObject

    override init() {}

    func someFunction(someArg:AnyObject) -> String {
        let returnVal = "You sent me \(someArg)"
        return returnVal
    }
}

你可以看看Swift & Cocoapods的帖子。基本上,我们需要创建一个桥接头文件,并将所有Objective-C头文件放在那里。然后我们需要从构建设置中引用它。之后,我们可以使用Objective-C代码。

let manager = AFHTTPRequestOperationManager()
manager.GET(
  "http://example.com/resources.json",
  parameters: nil,
  success: { (operation: AFHTTPRequestOperation!,
              responseObject: AnyObject!) in
      println("JSON: " + responseObject.description)
  },
  failure: { (operation: AFHTTPRequestOperation!,
              error: NSError!) in
      println("Error: " + error.localizedDescription)
  })

也可以看看苹果的文档Using Swift with Cocoa和Objective-C。

创建桥接头后,进入构建设置=>搜索“Objective-C桥接头”。

就在下面你会发现“Objective-C Generated Interface Header Name”文件。

在视图控制器中导入那个文件。

例子:在我的例子中:“Dauble-Swift.h”

使任何Swift类的NSObject子类也有意义,我更喜欢使用任何Swift类在Objective-C类中看到,如:

@objc(MySwiftClass)
@objcMembers class MySwiftClass {...}