如何访问objective-c文件中的swift类

use*_*613 5 iphone objective-c ios swift swift2

我有一个 swift 项目,我在项目中导入了一个单例、objective-c 编码的类。

我尝试导入 productname_swift.h 文件,但没有成功。

我如何访问该单例类中的 swift 类?

tec*_*erd 5

用 Swift 制作的项目:在 Objective C 中使用 Swift 类

要在 Objective C 中使用Swift 类,请按照给定的步骤操作:

  1. 创建一个名为User的 Objective C 类。
  2. 弹出窗口显示“您想配置 Objective-C 桥接标头吗”。选择创建桥接标头

在此输入图像描述

用户.h

#import <Foundation/Foundation.h>

@interface User : NSObject

+(id) sharedUser ;

@end
Run Code Online (Sandbox Code Playgroud)

用户.m

#import "User.h"
#import "SwiftInObjectiveC-swift.h"


@implementation User


//Singleton of User

+(id)sharedUser{

    static User *sharedUser = nil;
    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        sharedUser = [[self alloc] init];

        //Class Method of ViewController.swift
        [ViewController mySwiftClassFunction];


        //Instance Method of ViewController.swift
        ViewController *vc = [[ViewController alloc] init];
        [vc mySwiftFunction];

    });
    return sharedUser;
}

-(void) myObjcectivecMethod {

    ViewController *vc = [[ViewController alloc] init];
    [vc mySwiftFunction];

}
Run Code Online (Sandbox Code Playgroud)
  1. @objc在类名前面添加您的 .swift 类。

     import UIKit
    
     @objc class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // 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.
    }
    
    func mySwiftFunction() {
    
        print("Swift Function")
    }
    
    class func mySwiftClassFunction (){
    
        print("Swift Class Function")
    
    }
    
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 转到构建设置。

  3. 设置产品模块名称:ProjectName

在此输入图像描述

  1. 设置定义模块:是

在此输入图像描述

  1. 设置嵌入内容包含 Swift:是

在此输入图像描述

  1. 设置安装 Objective-C 兼容性标头:YES

在此输入图像描述

  1. 设置Objective-C 桥接头:SwiftInObjectiveC/SwiftInObjectiveC-Bridging-Header.h

在此输入图像描述

  1. 在*.m文件中导入自动生成的标头“ ProjectName-swift.h ” 。
  2. 清理并运行您的项目。
  3. 会起作用的!!!

请关注 Apple 的Mix and Match链接,了解详细信息。

在此输入图像描述