Swift calls C, C ++, Object-C, swift calls cobject-c
1. Swift calls C Language
A. First, add the CFile file named CHello in the project and generate a bridge file.
B. The project structure after creation is shown in:
B. Compile the interface method in CHello. h file, compile the implementation method in CHello. c, and introduce CHello. h In the SwiftCallC-Bridging-Header.h file.
CHello. h file
#ifndef __SwiftCallC__CHello__#define __SwiftCallC__CHello__#include <stdio.h>void sayHello();#endif /* defined(__SwiftCallC__CHello__) */
CHello. c file
#include "CHello.h"void sayHello(){ printf("hello\n");}
SwiftCallC-Bridging-Header.h files
#import "CHello.h"
2. Swift calls the OC Language
A. Similarly, add the object-c file named OCHello under the project. This is not required because file bridges have been created.
B. Compile the interface method in OCHello. h file, compile the implementation method in OCHello. c, and finally introduce the OCHello. h header file in the SwiftCallC-Bridging-Header.h file.
OCHello. h file
# Import <Foundation/Foundation. h> @ interface OCHello: NSObject // The method does not have parentheses. This is really not suitable --! -(Void) sayHello; @ end
OCHello. m file
#import "OCHello.h"@implementation OCHello-(void)sayHello{ NSLog(@"hello");}@end
SwiftCallC-Bridging-Header.h files
#import "CHello.h"#import "OCHello.h"
C. Finally, you can call Object-C in Swift code ~
import UIKitclass ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. var oc = OCHello() oc.sayHello() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. }}
3. Swift calls the C ++ Language
To call the c ++ code, you only need to change the original OCHello. change the m file to OCHello. mm, then you can reference the iostream header file in this file .... ^ The feel of c ++ instantly exists!
Finally, you can modify the implementation method slightly.
#import "OCHello.h"#include "iostream"using namespace std;@implementation OCHello-(void)sayHello{ cout<<"Hello"<<endl;}@end