How to call swift under OC, the best and simple practice

1. Create a new object-c project test and create a Person.swift class

Automatic prompt after creation:

Be brave and say no! Click Don't Create to ignore creating a bridging header file. Because oc calls swift, there is no need to import header files (swift only has .m implementation files). At this time, oc and swift are mixed, OC will access swift through a special macro, and the specific access of swift is through a header file as follows:

The default name can be changed, we changed it to Switch.h

2. Import the module macro file of swift

3. Write swift leaks to object-c

Tips: Pure swift classes that do not inherit NSObject cannot be accessed by OC, only methods and properties modified by @objc are visible to OC, and properties and methods must also be modified with public (decorate directly in front of the class with @objcMembers, the system It will automatically add @objec to the properties and methods of the class object to indicate that they can be accessed by OC.)

4. OC calls swift

I then dynamically added a label to allow OC to access and display the name property of Person.swift

//
//  ViewController.m
//  test
//
//  Created on 2022/9/12.
//

#import "ViewController.h"
#import <Swift.h>

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    Person *p =[[Person alloc]init];
    [p test];
    
    UILabel *label = [[ UILabel alloc] init];
    label.text = [p name];
    label.frame = CGRectMake(0,0,100,100) ;
    label.backgroundColor = [UIColor redColor];
    [self.view addSubview:label];

}

The result of the operation is as follows:

 These three letters are the string I assigned to name in Person.swift, please change it to helloworld by yourself!

Well, although it is done according to the tutorial, we still need to take care of the reaching party, download the demo address: https://download.csdn.net/download/xgocn/86514156

The specific points are not set by me, they are dynamically adjusted by csdn

Guess you like

Origin blog.csdn.net/xgocn/article/details/126820012