Variadic Functions in Objective-C

Variadic functions can be called with any number of trailing arguments. For example, fmt.Println is a common variadic function.

#import <Foundation/Foundation.h>

// Here’s a function that will take an arbitrary number of `int`s as arguments.
void sum(NSArray *nums) {
    NSLog(@"%@ ", nums);
    int total = 0;

    // Within the function, the type of `nums` is equivalent to `NSArray`.
    // We can call `count`, iterate over it with `for-in`, etc.
    for (NSNumber *num in nums) {
        total += [num intValue];
    }
    NSLog(@"%d", total);
}

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // Variadic functions can be called in the usual way with individual arguments.
        sum(@[@1, @2]);
        sum(@[@1, @2, @3]);

        // If you already have multiple args in an array,
        // apply them to a variadic function using like this.
        NSArray *nums = @[@1, @2, @3, @4];
        sum(nums);
    }
    return 0;
}

To run the program, compile the code and execute the binary.

$ clang -fobjc-arc -framework Foundation variadic-functions.m -o variadic-functions
$ ./variadic-functions
[1 2] 3
[1 2 3] 6
[1 2 3 4] 10

Another key aspect of functions in this language is their ability to form closures, which we’ll look at next.