Mutual invocation of Swift and OC

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.