Generics in Objective-C

Objective-C doesn’t have native support for generics like Go does. However, we can simulate some generic-like behavior using Objective-C’s dynamic typing and protocols. Here’s an approximation of the Go example in Objective-C:

#import <Foundation/Foundation.h>

// Protocol for comparable objects
@protocol Comparable <NSObject>
- (BOOL)isEqual:(id)object;
@end

// Function to find index of an element in an array
NSInteger ArrayIndex(NSArray *array, id<Comparable> value) {
    for (NSInteger i = 0; i < array.count; i++) {
        if ([value isEqual:array[i]]) {
            return i;
        }
    }
    return -1;
}

// Generic-like list implementation
@interface List : NSObject
@property (nonatomic, strong) NSMutableArray *elements;
- (void)push:(id)value;
- (NSArray *)allElements;
@end

@implementation List

- (instancetype)init {
    self = [super init];
    if (self) {
        _elements = [NSMutableArray array];
    }
    return self;
}

- (void)push:(id)value {
    [self.elements addObject:value];
}

- (NSArray *)allElements {
    return [self.elements copy];
}

@end

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        NSArray *s = @[@"foo", @"bar", @"zoo"];
        
        NSLog(@"index of zoo: %ld", (long)ArrayIndex(s, @"zoo"));
        
        List *lst = [[List alloc] init];
        [lst push:@10];
        [lst push:@13];
        [lst push:@23];
        NSLog(@"list: %@", [lst allElements]);
    }
    return 0;
}

In this Objective-C version:

  1. We define a Comparable protocol to simulate the comparable constraint in Go.

  2. The SlicesIndex function is replaced with ArrayIndex, which works with NSArray and objects conforming to the Comparable protocol.

  3. The generic List type is implemented as an Objective-C class that can hold any object type.

  4. The Push method is implemented as push:, and AllElements as allElements.

  5. In the main function, we demonstrate the usage of ArrayIndex and the List class.

To run this program, save it as a .m file (e.g., generics.m) and compile it with:

$ clang -framework Foundation generics.m -o generics
$ ./generics
index of zoo: 2
list: (
    10,
    13,
    23
)

Note that Objective-C’s lack of true generics means we lose some type safety compared to the Go version. The List class can hold any object type, and type checking is done at runtime rather than compile-time.

Objective-C doesn’t have a direct equivalent to Go’s generics, but this example demonstrates how to achieve similar functionality using Objective-C’s dynamic typing and protocols.