Swift calls the Objective C code

  • 2020-05-06 11:43:36
  • OfStack

Swift, the new programming language recently developed by iOS, has been well received in the iOS development community, with many tutorials and small examples at home and abroad.
While the Swift language is still evolving and changing a lot, and apple doesn't promise that the code it currently writes will be compatible in the future, it's still not holding back the enthusiasm of iOS developers.

Why does call Objective-C code
with Swift

Currently, applications written in Swift are only just ready to be submitted with the Xcode 6 GM version, while Objective-C has been apple's main development language for many years. Currently, no mature Swift libraries are available, so you can't write an application without calling Objective-C code.

How does call Objective-C code

The current apple solution is to use an Bridging-Header header file that references the Objective-C code to be used. Where Xcode automatically generates the header file name in the form of the project name -Bridging-Header.h. However, the file name format is not required and you are free to define it.

Xcode automatically generates scheme

Creating a new Swift project does not automatically generate the header file that calls Objective-C. However, you can create a new Objective-C file in your project, and Xcode will tell you whether to generate a corresponding header file to invoke Swift. The option is to automatically generate a header file in the format described above. You can delete the newly created empty Objective-C file and keep only this header file.
Fill in the header of the Objective-C file or library you want to call later in the bridge connector file.

custom solution

If you chose to cancel in the previous step, the subsequent creation of Objective-C file will no longer prompt. Or you may want to customize a file name instead of using the file name generated by Xcode.

Choose to create a new Header file. For example, it could be Hello.h
Then, in the project -- TARGETS, find Swift Compiler-Code Generation, there is an item, the key is Objective-C Bridging Header, in its value, fill in your header information.

1. You can drag the corresponding header file into the input box to fill in the value
2. Manually fill in the header file path to the input box, such as: Hello/Hello h

This way, you can use the corresponding header file to reference the Object-C code.


Related articles: