breaking out of a switch within a foreach loop closure

萝らか妹 提交于 2021-01-28 14:30:21

问题


I have the following code

 void onSelectionChangedFiredSources( Event event, var detail,
                                SelectCheckboxMenuComponent target)
  {
    // getItemModels returns a list of objects
      getItemModels( target.selectedItems )
        ..forEach( (item)
          {          
             switch( item.label )
             {
               case 'Ear':
                 toggleDialog( 'paper-dialog-transition-center',
                                $['ear-side-dialog']);
                 break;

               case 'Eye':
                 toggleDialog( 'paper-dialog-transition-center',
                                $['eye-side-dialog']);
                 break;

               case 'Nostril':
                 toggleDialog( 'paper-dialog-transition-center',
                                $['nostril-side-dialog']);
                 break;

               case 'Thorax':
                 toggleDialog( 'paper-dialog-transition-center',
                                $['thorax-side-dialog']);
                 break;

               default:
                 srcDataMap.add( item.label, item.selected);
             }   
          });
  }

When a case is triggered, I would like to break out of the foreach loop.

Note that each time the selection changes, all selections are return by the target.selectedItems expression. So if 'Ear' is the first selection, the loop is executed and when 'Eye' is then selected the list return will have both Ear and Eye. How is this best done? Thanks


回答1:


You can't break a forEach call.

You can't use break because it's not a loop. It's a function call, and break only works inside the current function.

You can't return, because that just continues with the next element.

You can throw to end the forEach, but that's hardly pretty.

What you can do instead is to not use forEach at all, and use a for-in loop instead, and then break out of that using a labeled break:

void onSelectionChangedFiredSources(Event event, var detail,
                                    SelectCheckboxMenuComponent target) {
  // getItemModels returns a list of objects
  var models = getItemModels(target.selectedItems);
  loop: for (var item in models) {
    switch (item.label) {
      case 'Ear':
      case 'Eye':
      case 'Nostril':
      case 'Thorax':
        toggleDialog('paper-dialog-transition-center',
                     $['${item.label.toLowerCase()}-side-dialog']);
        break loop;
      default:
        srcDataMap.add( item.label, item.selected);
    }   
  }
}

You need to use a labeled break because without a label it would only be breaking the switch statement.



来源:https://stackoverflow.com/questions/27110517/breaking-out-of-a-switch-within-a-foreach-loop-closure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!