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:
We define a
Comparableprotocol to simulate thecomparableconstraint in Go.The
SlicesIndexfunction is replaced withArrayIndex, which works withNSArrayand objects conforming to theComparableprotocol.The generic
Listtype is implemented as an Objective-C class that can hold any object type.The
Pushmethod is implemented aspush:, andAllElementsasallElements.In the
mainfunction, we demonstrate the usage ofArrayIndexand theListclass.
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.