OC调用Swift framework

在此记录下OC如何调Swift framework!

  1. 新建工程OCCallSwift,语言选择OC,如图:

     

    image.png

  2. 新建lib_swift module,语言选择Swift,如图:

     

    image.png

  3. 新建测试对象TestMethod.swfit,如下:

 

import Foundation

public typealias complete = (_ v1:Int,_ v2:Int)-> Int

public class TestMethod: NSObject {
    
    // 闭包表达式1
    @objc public var callback1:complete?
    // 闭包表达式2
    @objc public var callback2:((_ v1:Int,_ v2:Int)-> Int)?
    
    // 无参方法
    @objc public func test1() -> Void {
        print("test1 is run")
    }
    
    // 有参方法
    @objc public func test2(index:Int) -> Void {
        print("test2 is run \(index)")
    }
    
    // 尾随闭包方法
    @objc public func test3(a:Int,b:Int, callback:(Int)->Void) {
        return callback(a + b)
    }
    
    // 闭包方法1
    @objc public func test4() {
        guard let call = callback1 else {
            return
        }
        let result = call(2,3)
        print("callback1=\(result)")
    }
    
    // 闭包方法2
    @objc public func test5() {
        guard let call = callback2 else {
            return
        }
        let result = call(2,3)
        print("callback2=\(result)")
    }
}

注意事项:

方法由于是提供给OC调用需添加@objc修饰,public为暴露给OC试用的方法

  1. 在ViewController.m中进行调用,如下:

 

#import "ViewController.h"
// 导库
#import <lib_swift/lib_swift-Swift.h>

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    TestMethod *test = [[TestMethod alloc] init];
    [test test1];
    
    [test test2WithIndex:10];
    
    [test test3WithA:1 b:2 callback:^(NSInteger result) {
        NSLog(@"result=%ld",result);
    }];
    
    test.callback1 = ^NSInteger(NSInteger v1, NSInteger v2) {
        return v1 + v2;
    };
    [test test4];
    
    test.callback2 = ^NSInteger(NSInteger v1, NSInteger v2) {
        return v1 * v2;
    };
    [test test5];
}

@end

运行结果如下:

 

test1 is run
test2 is run 10
2020-06-05 16:56:57.269025+0800 OCCallSwift[14809:339123] result=3
callback1=5
callback2=6

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值