Swift is a new programming language for writing iOS and OS X applications released by Apple at WWDC in 2014. It can be mixed with Objective-C/C/C++ programming.

One. Objective-c calls C

Objective-c is a superset of C, so Objective-C is fully compatible with C, and you can write C code directly in Objective-C code without changing it.

Objective-c calls C++

Xcode requires the.mm extension of the source file to enable the objective-C ++ extension of the compiler. You can write BOTH C++ and Objective-C code in the.mm file, which supports most C++ features. Almost fully compatible with GNU C/C++.

Swift calls Objective-C

1. Add the bridge file

Add a new Header file to the project as a bridge file. The recommended name is {project_name} -bridge-header. h, where I named swiftmixeddemo-bridge-header. h, as shown in the picture:

2. Set objective-C Bridging Header

Select the project name, go to the Build Settings TAB, select All, and type bridging in the search box in the upper right to find the Objective-C Bridging Header, And set to {project_name} / {project_name} – Bridging – Header. H, here I set as SwiftMixedDemo/SwiftMixedDemo – Bridging – Header. H, as shown in figure:

3. Add the Objective-C file

Add the Objective-C files you need to import to your project, and then add the corresponding Header files to the bridge file swiftMixedDemo-bridge-header.h:

You can then call the code in the Objective-C file as normal.

4. Swift call C/C + +

And Swift cannot call C/C++ directly, but can call C/C++ indirectly by calling Objective-C code.

Objective-c calls Swift

Well, just reference the following header file where it needs to be called:

#import "{project_name}-Swift.h"
Copy the code

Note, however, that Swift 4’s @objc inference is turned off by default. If you want to expose it to OC, you need to manually add the @objc identifier before the class or property or method name.

PS: {project_name} indicates the project name.

The above.

Please correct any intellectual property rights, copyright issues or theoretical errors. https://juejin.cn/post/6844903529589522445 reprint please indicate the original author and the above information.