Search code examples
objective-cswitch-statementbreaklabeled-statements

iOS break loop with switch


I have a loop like this:

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];
    }

Of course, since Objective-C does not support loop labeling (at least, when I try, it throws a compile error saying Expected ';' after break statement), this doesn't work. Is there a way I can break a loop using a switch case in Objective-C? If not, what's a best practice with the same effect?


Solution

  • A solution is to put the whole expression into a method and exit the switch statement with return.

    - (void)checkSomething:(id)object
    {
      for(X *y in object)
      {
        switch(y.num)
        {
          case ShouldDoSomething:
            something();
            break;
          case ShouldStopNow:
            return;
            break;
        }
        somethingElse();
      }
    }
    

    Another solution is using a boolean flag

    for(X *y in Z)
      {
        BOOL willExitLoop = false;
        switch(y.num)
        {
          case ShouldDoSomething:
            something();
            break;
          case ShouldStopNow:
            willExitLoop = true;
            break;
        }
        if (willExitLoop) break;
        somethingElse();
      }