Objective-C:如何在集合枚举块中使用 `continue`?

44
如果我有一个NSArray并且我使用enumerateUsingBlock循环遍历数组中的元素,但在某些情况下我需要跳过循环体并继续执行下一个元素,是否有块中的等效continue,或者可以直接使用continue吗?
谢谢!
更新:
只是想澄清,我想做的是:
for (int i = 0 ; i < 10 ; i++)
{
    if (i == 5)
    {
        continue;
    }
    // do something with i
}

我需要的是块级作用域中的continue等效语句。

3个回答

75

块(Block)与匿名函数类似,因此您可以使用

return

来退出返回类型为void的函数。


嗨,请看一下我的更新,这就是我想表达的意思,对于误解我感到抱歉。 - hzxu
5
好的,但是return在标准循环中不是等价于break吗?如果是这样,那么continue的等价物是什么?break完全跳出循环,而continue跳到下一次迭代。在枚举块中如何实现这个功能? - shmim
19
return没有*stop = YES相当于在for循环中使用continuereturn*stop = YES相当于使用break - Ken Thomases

10
使用"continue"来做到这一点,当使用快速枚举时。
示例代码:
NSArray *myStuff = [[NSArray alloc]initWithObjects:@"A", @"B",@"Puppies", @"C", @"D", nil];

for (NSString *myThing in myStuff) {
    if ([myThing isEqualToString:@"Puppies"]) {
        continue;
    }

    NSLog(@"%@",myThing);

}

并输出:

2015-05-14 12:19:10.422 test[6083:207] A
2015-05-14 12:19:10.423 test[6083:207] B
2015-05-14 12:19:10.423 test[6083:207] C
2015-05-14 12:19:10.424 test[6083:207] D

没有任何小狗出现。


5

在块中不能使用continue语句,否则会出现错误:error: continue statement not within a loop。应该使用return语句。

[array enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop) {
        /* Do something with |obj|. */
        if (idx==1) {
            return;
    }
        NSLog(@"%@",obj);
    }];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接