我有一个这样的循环:
label: for(X *y in z)
{
switch(y.num)
{
case ShouldDoSomething:
[self somethingWithX:y];
break;
case ShouldStopNow:
y = [self valWhenStopped];
break label;
}
[val append y];
}
当然,由于Objective-C不支持循环标记(至少,当我尝试时,它会抛出一个编译错误,说Expected ';' after break statement
),这不起作用。 有没有办法在Objective-C中使用switch case打破循环?如果没有,那么具有相同效果的最佳做法是什么?
答案 0 :(得分:4)
解决方案是将整个表达式放入方法中并使用return退出switch语句。
- (void)checkSomething:(id)object
{
for(X *y in object)
{
switch(y.num)
{
case ShouldDoSomething:
something();
break;
case ShouldStopNow:
return;
break;
}
somethingElse();
}
}
另一个解决方案是使用布尔标志
for(X *y in Z)
{
BOOL willExitLoop = false;
switch(y.num)
{
case ShouldDoSomething:
something();
break;
case ShouldStopNow:
willExitLoop = true;
break;
}
if (willExitLoop) break;
somethingElse();
}
答案 1 :(得分:1)
您还可以使用标志:
for(...) { BOOL stop = NO ; switch(...) { case x: break ; case y: stop = YES ; break ; } if ( stop ) { break ; } somethingElse(); }
答案 2 :(得分:0)
我认为您正在寻找continue
:
for(X *y in Z)
{
switch(y.num)
{
case ShouldDoSomething:
something();
break;
case ShouldStopNow:
continue; //-- this will break the switch and reenter the for loop with the next element
}
somethingElse();
}