6

How would you stop fast enumeration once you have gotten what your looking for.

In a for loop I know you just set the counter number to like a thousand or something. Example:

for (int i=0;i<10;i++){
    if (random requirement){
        random code
        i=1000;
    }
}

so without converting the fast enumeration into a forward loop type thing (by comparing i to the [array count] how can you stop a fast enumeration in the process?

vikingosegundo
  • 52,040
  • 14
  • 137
  • 178
bmende
  • 741
  • 1
  • 11
  • 24
  • 5
    Use a `break;` statement. You can use these in your normal for-loops too. – Dustin Aug 13 '12 at 16:49
  • 3
    Who told you to _reset the index variable_ in order to stop a `for` loop?! We're going to have to suspend their programming license. – jscs Aug 13 '12 at 17:21
  • 3
    Oh, well; you've now completed your re-education process and your license is again in good standing. Welcome back. /toungue-in-cheek Actually, it's better that it was you figuring that out on your own -- it's rather ingenious, if you don't know about the `break` statement. – jscs Aug 13 '12 at 18:09
  • 1
    this approach is really not that bad, as it work similar to breaking out of a while-loop, the most general loop. – vikingosegundo Aug 13 '12 at 21:14
  • @vikingosegundo while loop the most general one? I dont think so, I havent even used one while in my entire coding career – bmende Aug 13 '12 at 23:14
  • either that or im programming bad – bmende Aug 13 '12 at 23:14
  • 2
    I mean, it is the most basic one. you can write every for-loop as a while-loop. or a do-while-loop – vikingosegundo Aug 13 '12 at 23:40

4 Answers4

11

from the docs

for (NSString *element in array) {
    if ([element isEqualToString:@"three"]) {
        break;
    }
}

if you want to end enumeration when a certain index is reached, block-based enumeration might be better, as it give you the index while enumerating:

[array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    //…
    if(idx == 1000) 
        *stop = YES;
}];
vikingosegundo
  • 52,040
  • 14
  • 137
  • 178
2
for (id object in collection) {
  if (condition_met) {
    break;
  }
}
Jesse Black
  • 7,966
  • 3
  • 34
  • 45
1

Couldn't you just use a break statement?

for (int x in /*your array*/){
    if (random requirement){

        random code
        break;
    }
}
1

Just adding that for nested loops, a break on an inner loop breaks just that loop. Outer loops will continue. If you want to break out completely you could do so like this:

BOOL flag = NO;
for (NSArray *array in arrayOfArrays) {
    for (Thing *thing in array) {
        if (someCondition) {
            // maybe do something here
            flag = YES;
            break;
        }
    }
    if (flag) {
        break;
    }
}
Murray Sagal
  • 8,454
  • 4
  • 47
  • 48