Objective-C 调用 Swift

Swift 类

Swift类定义前加入@objc关键字,并使类继承自NSObject

@objc class S : NSObject{
    func m() {
        print(__FUNCTION__)
    }
}

在调用Swift代码的Objc文件中加入名类似为"xxx-Swift.h"的头文件

头文件具体的名字可在 设置选项:

{project} - {targets} - {build settings} - {swift compiler - code generation} - {Objective-C Generated Interface Header Name}

objc调用swift头文件名


 #import "objc_swift-Swift.h"
int main(int argc, const char * argv[]) {
   @autoreleasepool {
        S* s = [[S alloc]init];
        [s m];
    }
    return 0;
 }

Swift 调用 Objective-C

创建桥接文件

创建桥接文件

选择Create Bridging Header

桥接文件在如下设置位置

{project} - {targets} - {build settings} - {swift compiler - code generation} - {Objective-C Bridging Header}

将要调用的ObjC类头文件import至桥接文件中

//
//  Use this file to import your target's public headers that you would like to expose to Swift.
//

 #import "O.h"

ObjC 代码

.h 文件

@interface O : NSObject
-(void)m;
@end

.m 文件

@implementation O
-(void)m {
    NSLog(@"%s", __FUNCTION__);
}
@end

swift 文件

@objc class S : NSObject{
    let o:O = O()
    func m() {
        o.m()
        print(__FUNCTION__)
    }
}

示例工程

objc-swift

标签: objc, swift, cocoa, xos
日期: 2016-04-01 17:30:06, 8 years and 289 days ago
留言

回复不允许使用html标签

通过电子邮件通知我有后续评论.