简体   繁体   中英

Using for in how can one refer to next object in array

While the "for in" loop is running, is it possible to look up the value of the next "string"?

Lets say you had an array called myArrayOfStrings that had the following values in it:

0 "Apple" 1 "Pear" 2 "Orange" 3 "Grape"

And you wanted to iterate over the array using a "for in" loop:

for (NSString* string in myArrayOfStrings) { NSLog(string); }

Is there anyway, inside of the "for in" loop to look of the value of the next string while it's running? Lets say it was currently looking at the 1 "Pear" string. Would there be anyway to lookup the value of the next string 2 "Orange"?

While this is not directly achievable using a foreach-style loop in objective c, there are a couple ways to accomplish the same task.

Please assume that

NSArray *myArrayOfStrings = @[@"Apple", @"Pear", @"Orange", @"Grape"];

Standard For Loop

for (int i = 0; i < [myArrayOfStrings count]; i++) {
    NSString *string = [myArrayOfStrings objectAtIndex:i];
    NSString *next_string = @"nothing";
    if (i + 1 < [myArrayOfStrings count]) { // Prevent exception on the final loop
        next_string = [myArrayOfStrings objectAtIndex:i + 1];
    }
    NSLog(@"%@ comes before %@", string, next_string);
}

Object Enumeration

[myArrayOfStrings enumerateObjectsUsingBlock:^(NSString *string, NSUInteger idx, BOOL *stop) {
    NSString *next_string = @"nothing";
    if (idx + 1 < [myArrayOfStrings count]) { // Prevent exception on the final loop
        next_string = [myArrayOfStrings objectAtIndex:idx + 1];
    }
    NSLog(@"%@ comes before %@", string, next_string);
}];

Both of these options output:

Apple comes before Pear
Pear comes before Orange
Orange comes before Grape
Grape comes before nothing

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM