Fixing Objective-C syntax
With a couple of additions, Objective-C’s syntax could be much nicer. Here are some ideas. Most of this is me hideously abusing the @ sign to avoid collision with built in C functions.
I definitely don’t want to lose compatibility with C, nor backward compatibility with old objective-C code. Nor am I against verbosity in general: I love the long method names in Cocoa, because when you encounter one for the first time it’s easier to work out what it does and what to pass in. But for a certain number of operations that are performed many times in most code, we could tighten things up a bit.
I wrote this after reading Regarding Objective-C & Copland 2010, where Objective-C was failed on “Succinct syntax for common operations”.
NSNumber literals:
[array addObject:@6];
Arithmetic operations on objects:
NSNumber *num = @5; NSNumber *anotherNum = num @+ @9;
If this one could automatically detect whether the right hand side is a primitive or an object, we could forgo the second @. How about it, preprocessor designing wizards?
Operator overloading:
- (id)add:(id)anObject { }
The supported arithmetic operators are overloadable by overriding their method on the class in question. Since this overloading only applies to the @+ operators that act on objects, it won’t cause as much chaos as in some other languages.
Equality:
if (anObject @== anotherObject) { }
Simply calls isEqual:
Array creation:
NSArray *array = @{anObject, anotherObject};
Shortcut to create a new NSArray. Note you don’t need a nil at the end — this is all done in preprocessing so it can quite easily count the number of items!
Mutable array creation:
NSMutableArray *array = @M{anObject, anotherObject};
Shove an M in there to make the array mutable.
Dictionary creation:
NSDictionary *dict = @{@"key", aValue, @"anotherKey", anotherValue};
There may be a better way to do this one rather than just comma-separated, but I think this is the easiest. Again, no nil needed.
String concatenation:
NSString *string = aString @+ anotherString;
By default, NSString can implement add: to return a new autoreleased concatenated string. Since it can just append the description of the passed in object, then concatenating a string and a number by this method will work.
These are just some ideas. I’d be interested in hearing any others!