Expose swift variadic parameter to Objective-C

后端 未结 1 1011
后悔当初
后悔当初 2021-01-02 16:31

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          


        
相关标签:
1条回答
  • 2021-01-02 16:53

    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.

    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]) {
    
        }
    }
    

    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
    
    0 讨论(0)
提交回复
热议问题