将快速可变参数传递给Objective-C [英] Expose swift variadic parameter to Objective-C

查看:97
本文介绍了将快速可变参数传递给Objective-C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在研究一种快速的动态框架,该框架将用于Objective-C应用程序.

I am currently working on a swift dynamic framework which will be used for an objective-c application.

我已经创建了此方法(签名):

I've created this method (signature):

public init(buttons: ActionButton...) {
///code
}

但是,永远无法从使用框架的Objective-C应用程序访问(可见)此方法.添加时

However this method is never accessible (visible) from the objective-c app that is using the framework. When adding

@objc

在方法声明xcode前面给出错误

in front of the method declaration xcode gives the error

由于方法具有可变参数,因此无法将其标记为@objc"

"Method cannot be marked @objc because it has a variadic parameter"

因此,如果我正确理解,快速变参参数就无法暴露给目标c.因此,我要问的问题是: 还有其他方法(CVArgList?)来获得相同的功能吗?

So if I understand correctly swift variadic parameters are not exposable to objective c. The question I am therefore asking is: Is there any other way (CVArgList?) to get the same functionality?

我知道我可以使用数组,但我不希望使用此功能.

I know i can use Arrays but I'd rather not for this function.

谢谢.

推荐答案

您可以将C中的可变参数函数桥接到Swift,但不能反过来.参见

You can bridge variadic functions in C to Swift, but not the other direction. See Using Swift with Cocoa and Objective-C:Interacting with C APIs:Variadic Functions for more on that.

但这并不难手动实现.只需创建该方法的数组版本,然后将所有可变参数形式传递给它即可. Swift的第一名:

But this isn't that hard to implement by hand. Just create an array version of the method and pass all the variadic forms to it. First in Swift:

public class Test: NSObject {
    convenience public init(buttons: String...) {
        self.init(buttonArray: buttons)
    }

    public init(buttonArray: [String]) {

    }
}

然后通过一个类别向ObjC公开.

And then expose to ObjC through a category.

@interface Test (ObjC)
- (instancetype) initWithButtons:(NSString *)button, ...;
@end

@implementation Test (ObjC)

- (instancetype) initWithButtons:(NSString *)button, ... {
    NSMutableArray<NSString *> *buttons = [NSMutableArray arrayWithObject:button];
    va_list args;
    va_start(args, button);

    NSString *arg = nil;
    while ((arg = va_arg(args, NSString *))) {
        [buttons addObject:arg];
    }

    va_end(args);
    return [self initWithButtonArray:buttons];
}

@end

这篇关于将快速可变参数传递给Objective-C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆