简体   繁体   English

在for中如何使用for引用数组中的下一个对象

[英]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"? 当“for in”循环正在运行时,是否可以查找下一个“字符串”的值?

Lets say you had an array called myArrayOfStrings that had the following values in it: 假设您有一个名为myArrayOfStrings的数组,其中包含以下值:

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

And you wanted to iterate over the array using a "for in" loop: 并且您希望使用“for in”循环遍历数组:

for (NSString* string in myArrayOfStrings) { NSLog(string); for(NSAtring * 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? 无论如何,在“for in”循环内部查看下一个字符串运行时的值是什么? Lets say it was currently looking at the 1 "Pear" string. 让我们说它目前正在看1“梨”字符串。 Would there be anyway to lookup the value of the next string 2 "Orange"? 无论如何都要查找下一个字符串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. 虽然在目标c中使用foreach-style循环无法直接实现,但有几种方法可以完成相同的任务。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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