2006-03-19 13:30:41 Arrays and foreach
NOTE: This page was written in the pre-Objective 2.0 days, when I was working on my own set of changes to Objective-C. My project has since been abandoned in favor of solutions made available both by Objective-C 2.0 and by F-Script.


Recently working code from the parser, using the current formulations, very much open to better syntax formulations.

At least for right now, the @ symbol is used to designate a syntax short-cut, just as @"…" does now. @( … ) is for NSArrays, @{ … } for NSDictionaries and @< … > for NSSets (though that does look odd, even in ObjC land). Substituting @@ for @ makes the object mutable. Using @ before an integer or a float will auto-create NSNumbers. I'm not with this syntax yet, especially that dictionary key/value pair order seems inverted, and :: just seems to make the expressions less readable.

A slightly overly-compact test script is below:
( objc )
  1  NSArray *stuff = @( @"this", @( @"how", @3 ) );
2 NSMutableArray *otherStuff = @@( @"this", @"working?", @22.17 );
3 NSDictionary *lookup = @{ @"we're #1!" :: @1,
4 @@{ @"Ocean", @< @4, @3.142 > } :: @11 };
5
6 foreach( item in stuff )
7 print "%s\n", [[item description] cString];
8
9 foreach( this in otherStuff )
10 print "%s\n", [[this description] cString];
11
12 foreach( key, value in lookup )
13 print "%s -> %s\n", [[key description] cString], [[value description] cString];


I put in the unnecessary nesting to make sure my code could unroll everything correctly. The output, which may make the code less opaque, is:

( objc )
  1  this
2 (how, 3)
3 this
4 working?
5 22.17
6 1 -> we're #1!
7 11 -> {<NSCFSet: 0x504c90> (3.142, 4) = Ocean; }


It was interesting getting the nestings to work out right in the parser with the foreach, which were my own variation on the attempts made by Louie and Rentzsch. Though not currently implemented here, one can use a specific strongly typed class for the iterator object.

Possible alternative to the NSDictionary line could look like this:
  1  lookup = @{ @1 => @"testing", @11 => @@{ @"Ocean" => @< @4, @3.142 > } }

though this will make for a more complicated parsing task.

(As a minor note, I started using the c99 flag with the gcc.)
Leave a comment