Zigii Wong
Zigii Wong

Reputation: 7826

Variadic method in Swift

Objective C Code:

- (instancetype)initWithInts:(int32_t)int1, ... {
    va_list args;
    va_start(args, int1);
    unsigned int length = 0;
    for (int32_t i = int1; i != -1; i = va_arg(args, int)) {
        length ++;
    }
    va_end(args);
    ...
    ...
    return self;
}

This code is used to count the numbers of method's parameters.

Swift Code:

convenience init(ints: Int32, _ args: CVarArgType...) {
    var length: UInt = 0
    self.init(length: args.count)
    withVaList(args, { _ in
        // How to increase length' value in loop?
    })
}

What's the best practise to use withVaList to loop through the argument list with a CVaListPointer? Help is very appreciated.

Upvotes: 2

Views: 413

Answers (2)

Zigii Wong
Zigii Wong

Reputation: 7826

convenience required init(args: Int32...) {

}

If you define your func parameter following by three dots ..., you will notice args is actually a [Int32] type.

So just do casting likes Array, i.e. args.count, for i in args.

Upvotes: 1

Gabriele Petronella
Gabriele Petronella

Reputation: 108101

How about just

convenience init(args: Int...) {
  return args.count
}

Upvotes: 3

Related Questions