Functions in Objective-C

Functions are central in Objective-C. We’ll learn about functions with a few different examples.

#import <Foundation/Foundation.h>

// Here's a function that takes two NSInteger values and returns
// their sum as an NSInteger.
NSInteger plus(NSInteger a, NSInteger b) {
    // Objective-C, like Go, requires explicit returns.
    return a + b;
}

// In Objective-C, we typically use methods instead of standalone functions.
// Here's a method that takes three NSInteger values and returns their sum.
@interface Calculator : NSObject
+ (NSInteger)plusPlus:(NSInteger)a with:(NSInteger)b and:(NSInteger)c;
@end

@implementation Calculator
+ (NSInteger)plusPlus:(NSInteger)a with:(NSInteger)b and:(NSInteger)c {
    return a + b + c;
}
@end

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // Call a function just as you'd expect, with name(args).
        NSInteger res = plus(1, 2);
        NSLog(@"1+2 = %ld", (long)res);
        
        // For methods, we use Objective-C's message sending syntax.
        res = [Calculator plusPlus:1 with:2 and:3];
        NSLog(@"1+2+3 = %ld", (long)res);
    }
    return 0;
}

To run the program, save it as functions.m and compile it with:

$ clang -framework Foundation functions.m -o functions
$ ./functions
2023-06-08 12:34:56.789 functions[12345:67890] 1+2 = 3
2023-06-08 12:34:56.790 functions[12345:67890] 1+2+3 = 6

There are several other features to Objective-C functions and methods. One is multiple return values, which we can achieve using structures or objects.