Consider the following statement:
for (NSString *string in anArray) {
NSLog(@"%@", string);
}
How can I get the index of string
in anArray
without using a traditional for
loop and without checking the value of string
with every object in anArray
?
Arrays are guaranteed to iterate in object order. So:
NSUInteger index = 0;
for(NSString *string in anArray)
{
NSLog(@"%@ is at index %d", string, index);
index++;
}
Alternatively, use the block enumerator:
[anArray
enumerateObjectsUsingBlock:
^(NSString *string, NSUInteger index, BOOL *stop)
{
NSLog(@"%@ is at index %d", string, index);
}];