Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you stop fast enumeration?

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?

like image 927
bmende Avatar asked Aug 13 '12 16:08

bmende


4 Answers

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;
}];
like image 98
vikingosegundo Avatar answered Nov 15 '22 14:11

vikingosegundo


for (id object in collection) {
  if (condition_met) {
    break;
  }
}
like image 35
Jesse Black Avatar answered Nov 15 '22 14:11

Jesse Black


Couldn't you just use a break statement?

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

        random code
        break;
    }
}
like image 22
Matthew Daiter Avatar answered Nov 15 '22 12:11

Matthew Daiter


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;
    }
}
like image 1
Murray Sagal Avatar answered Nov 15 '22 14:11

Murray Sagal