I'd like to propose an extension to the fast enumeration behaviour for Objective-C 2. This allows you to efficiently iterate over objects in a collection, but it would also be convenient in a great many cases to use the same mechanism to iterate over things that contain collections of primitive types, such as strings. Indeed, the iteration method is conceptually very similar to the -getBytes:range: and getCharacters:range: methods on NSData and NSString, respectively.
I've attached a diff (please do not commit as is!) which give a proof of concept implementation of a generalisation of fast enumeration to permit this. This generalises the method use for fast enumeration to this:
- (NSUInteger)countByEnumeratingWithState: (NSFastEnumerationState*)state
type: (const char*)type
This replaces the the object:(id*) parameter with two arguments; one a pointer to the buffer, the other an Objective-C type encoding of a single element in the array. If you call it with something like this:
for (unichar a in @"Foobar!")
The first parameter will be an array of len unichars, the third element will be "S" (the type encoding of unichar, which is a typedef for unsigned short).
I could add this as a GNU extension, but it would be more useful if it were supported by Apple as well. Note that this should have no impact on existing code: currently both clang and GCC raise an error with non-object element types, and my diff generates the old method for object return types.
I'm also tempted to suggest generalising it still slightly further by permitting a range for enumeration to be specified (this would, of course, only be relevant for ordered collections), as this currently requires falling back to very slow enumeration. I'm not sure what the best syntax for this would be though, maybe something like:
for (id a in array[1..30])
for (id a in array range 1,30)
Comments, (constructive) criticisms, and suggestions welcome,
fenum.m (1.89 KB)
clang.diff (3.68 KB)