iOS 用开关打破循环

iOS break loop with switch

我有一个这样的循环:

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 来打破循环? 如果没有,具有相同效果的最佳实践是什么?

一个解决方案是将整个表达式放入一个方法中,然后使用 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();
  }

您还可以使用标志:

for(...)
{
    BOOL stop = NO ;
    switch(...)
    {
        case x:
            break ;
        case y:
            stop = YES ;
            break ;
    }
    if ( stop ) { break ; }
    somethingElse();
}

我想你在找 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();
}