0

If I write:

 for (NSString* word in self.words)
{

}

And I want to keep track of my position in the array, how can I do that? Of course, I know I can just create an int and increment it as I loop, a.k.a. the old-fashioned way. I guess I'm just looking to see if there's an opportunity here to learn something. Like in python we have the handy enumerate() function for this sort of thing which gives you indices paired with objects.

temporary_user_name
  • 35,956
  • 47
  • 141
  • 220

1 Answers1

1

You could use [words indexOfObject:word]; but caution: if you have equal object in an array, it will return the first object's index. also this shows, that it is awfully inefficient — if will iterate over the array for each call.

better:

[words enumerateObjectsUsingBlocks:^(NSString *word,
                                     NSUInteger idx,
                                     BOOL *stop)
{
    //
}];

as it gives you enumeration AND the index at the same time.

documentation

vikingosegundo
  • 52,040
  • 14
  • 137
  • 178
  • 1
    I recommend that you just remove the first paragraph. There's no reason to even bring up the awful `-indexOfObject:` approach. – Ken Thomases Nov 20 '14 at 23:37
  • I think it is better to keep it, as otherwise OP might check the documentation and finds `indexOfObject:` but doesn't know of the downside, as it is not clearly stated there. – vikingosegundo Nov 21 '14 at 09:21