假设我有一个包含五种情况的switch语句,但只调用了两种真正的方法,如下所示:
switch (condition) {
case conditionOutcome1:
[self firstMethod];
break;
case conditionOutcome2:
[self secondMethod];
break;
case conditionOutcome3:
[self firstMethod];
break;
case conditionOutcome4:
[self firstMethod];
break;
case conditionOutcome5:
[self secondMethod];
break;
default:
break;
}
将案件分组是否安全,如此?
switch (condition) {
case conditionOutcome1:
case conditionOutcome3:
case conditionOutcome4:
[self firstMethod];
break;
case conditionOutcome2:
case conditionOutcome5:
[self secondMethod];
break;
default:
break;
}
它工作正常,但我之前从未在objective-c中使用它,所以我想确保通过保存几行代码来避免任何问题。
谢谢!
答案 0 :(得分:11)
只需添加其他答案,它就称为 fallthrough ,您可以阅读here。
答案 1 :(得分:9)
是的,这样做很好。
我以前用过它。它会停止重复代码。
答案 2 :(得分:9)
是100%安全使用
开关(条件){
case conditionOutcome1: case conditionOutcome3: case conditionOutcome4: [self firstMethod]; break; case conditionOutcome2: case conditionOutcome5: [self secondMethod]; break; default: break; }
对于要执行相同操作集(重复代码)的多个case
,始终使用此方法。
所有cases
将被执行,直到遇到break
。