Note that this is merely an academic question.
In Ruby, you can access array and dictionary(hash) elements conveniently:
value = myHash['myKey']
In Objective C, you need a method call:
value = [myDict objectForKey:@"myKey"];
How might one override some type of brackets or define a macro to bring the Objective C syntax closer to Ruby's?
Just an update:
Starting with iOS 6 I guess, you CAN use such a syntax:
value = dictionary[@"key"];
This is equivalent to
value = [dictionary objectForKey:@"key"];
Moreover, if we're talking about NSMutableDictionary, you can add new objects into a dictionary like this:
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc]init];
dictionary[@"a"] = @"A";
NSLog(@"%@",dictionary[@"a"]);
What you are trying to do requires a language feature called "operator overloading". Objective-C does not allow for operator overloading because the designers of the language felt that operator overloading was harmful more often than it was helpful.
C++ does allow for operator overloading, so one way to get the syntax you want is to wrap your collections in C++ classes and use those instead. To switch to Objective-C++, just change your implementation files' extensions from .m to .mm.
Personally, I would recommend against using C++ wrappers around collections because it will make your code harder for other Objective-C programmers to read and it will break some of the more advanced features of Xcode. For example, you will no longer be able to use the refactor tools, because Xcode will not be able to parse your code correctly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With