Swift after four years of development has become mature, it is time to learn, thank the company Swift Big Brother's generous enlighten. The heart has a sense of record, if there is insufficient to welcome criticism.
New Swift Project
Create a new swift, OC class file
You can create a bridge header file when you create a new OC file, or create a new bridge connector file yourself.
If you do not create a bridging file,
1. Create a header file: HeaderFileForSwiftAndOC.h
2. Find the path: project target, Bulid Settings, objective-c bridging Header
3. Fill in:$ (swift_module_name)/headerfileforswiftandoc.h
Fill in the code in the swift file with the OC file OC
OCClass.h
#import <Foundation/Foundation.h>@interface OCClass : NSObject- (void)ocFunction:(NSString *)str;@end
Occlass.m
#import "OCClass.h"#import "SwiftAndOC-Swift.h"//新建swift项目时默认创建,包含了所有swift文件引用@implementation OCClass- (void)ocFunction:(NSString *)str{ NSLog(@"\noc func par - str = %@",str); SwiftObj *swiftObj = [[SwiftObj alloc]init]; [swiftObj swiftFuncWithPar:@"OC -> swift"];}@end
Swift
Viewcontroller.swift
import UIKitclass ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let ocObj = OCClass(); ocObj.ocFunction("swift -> OC"); // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. }}
Swiftobj.swift
import UIKitclass SwiftObj: NSObject { @objc func swiftFunc(par:String){//@objc 很重要 必须写 不然oc调用时找不到该方法 print("swift func par = \(par)"); }}
Run the project
Controller printing
2018-06-20 18:01:19.346937+0800 SwiftAndOC[6803:243390] oc func par = swift -> OCswift func par = OC -> swift
? ?
? ?
? ?
Links: Technical Blog??????? Jane Book homepage
Mutual invocation of Swift and OC