在Objective-C中执行swift代码

时间:2015-12-22 11:52:26

标签: objective-c swift ios9

当我在Objective-C中执行Swift方法时,该方法内部的代码不会运行。

例如:我想打开一个新视图或启用一个按钮。

Objective-C代码:

Principal *myClass = [[Principal alloc] init];
[myClass getData];

Swift代码:

func getData() {
    let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
    let vc: UIViewController = storyboard.instantiateViewControllerWithIdentifier("MenuViewController") as UIViewController
    dispatch_async(dispatch_get_main_queue(), {
        self.presentViewController(vc, animated: true, completion: nil)
    })
}

2 个答案:

答案 0 :(得分:1)

确保使用@objc关键字标记您的Swift类,以便它们可供您的ObjC使用。

import Foundation

@objc class TestClass {
class func new() -> TestClass {
    return TestClass()
}

func testFunction() {
    println("This function works")
}
}

这是Objective-C客户端:

#import "AppDelegate.h"
#import "TestProject-Swift.h"
@implementation AppDelegate
 - (BOOL)application:(UIApplication *)application 
    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    TestClass *instance = [TestClass new];
    [instance testFunction];
    return YES;
}
@end

这里的秘密是在这种情况下使用“-Swift.h”扩展名导入目标名称“TestProject”。 Xcode为您构建了这个并将其隐藏在派生数据的幕后。对于上面的例子,我的遗留在:DerivedData / TestProject-aqpeqeuqusyzdtcqddjdixoppyqn / Build / Intermediates / TestProject.build / Debug-iphoneos / TestProject.build / DerivedSources / TestProject-Swift.h

答案 1 :(得分:0)

您需要在项目中创建一个标题(.h文件)并导入所需的所有类。

您的头文件看起来像。

#ifndef ProjectName_Bridging_Header_h
#define ProjectName_Bridging_Header_h

#import "Principal.h"

在构建设置中,您需要将头文件名设置为Objective-C Bridging Header

喜欢这个。 enter image description here