This is the mail archive of the gcc@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: Syntactic sugar to access arrays and hashes in Objective-C


Hi gcc'ers,

I was wondering if it would be a useful extension to Objective-C expand the [] operator
to support array and hash references to NSArray and NSDictionary classes directly to
greatly improve the readability of code:


NSArray<AVAudioPlayer *> *players = [NSArray arrayWithObjects:..., nil];

[players[0] play]; // expanded by compiler to: [(AVAudioPlayer *) [players objectAtIndex:0] play];
players[0] = aPlayer // expanded to: [players replaceObjectAtIndex:0 withObject:aPlayer]; or for NSDictionary:


NSDictionary<AVAudioPlayer *> *playersDict = [NSDictionary ....];

[playersDict[@"playerOne"] play]; // -> [(AVAudioPlayer *)[playersDict objectForKey:@"playerOne"] play];
playersDict[@"playerTwo"] = aPlayer; // becomes: [players setObject:aPlayer forKey:@"playerTwo"];


This also makes use of a form of templates for Objective-C containers which might also be a useful extension.

@interfcae NSArray<T> : NSObject {
- (T)objectAtIndex:(NSUInteger)index;
@end

@interface NSMutableObject<T> : NSArray {
- (void)replaceObjectAtIndex:(NSUInteger)index withObject:(T)anObject
@end

Where not specified, type T would default to (id) for backward compatibility.

I've looked at the code and such an extension would involve code generation inside
the subscript operator which looks difficult but if you want me to have a go and
can provide some pointers let me know. I know this introduces coupling between
the compiler and the runtime but I would have thought the benefits outweighed this.


Perhaps classes which wish to support subscripting make methods available by convention:

for NSArray:
- (id)operatorSubscriptInt:(NSUInteger)index;
- (id)operatorSubscriptObject:(id)key;

for NSDictionary
- (id)operatorSubscriptInt:(NSUInteger)index setValue:(id)anObject;
- (id)operatorSubscriptObject:(id)key setValue:(id)anObject;

I know, it sounds like one step on the way to operator overloading....

Best Regards & Thanks for your work,

John Holdsworth


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]