回答
int counter = 0;
if (condition1) counter++;
if (condition2) counter++;
if (condition3) counter++;
if (condition4) counter++;
if (condition5) counter++;
if (condition6) counter++;
if (counter >= 3) {
// something
}
你可以做到这一点是:
int validated=0;
if(condition1){
validated++;
}
if(condition2){
validated++;
}
if(condition3){
validated++;
}
if(condition4){
validated++;
}
if(condition5){
validated++;
}
if(condition6){
validated++;
}
if(validated>=3){
//do your stuffs
}
+1为更快:) – DrummerB 2013-03-19 17:14:29
你可以尝试计算正确的条件:
伪代码:已经给了
int counter = 0;
if(A) counter++;
if(B) counter++;
if(C) counter++;
if(D) counter++;
if(E) counter++;
if(F) counter++;
if(counter >= 3){
//do stuff here
}
counter = 0;
'== true'?是吗? – 2013-03-19 17:15:20
geez,你们很快。 – adamup 2013-03-19 17:16:33
可能是(!(A == true)== 0) – 2013-03-19 17:16:49
除了答案,这是一个更灵活的解决方案,适用于多种条件:
int conditions[6] = {condition1, condition2, condition3,
condition4, condition5, condition6};
int counter = 0;
for (int i = 0; i < sizeof(conditions)/sizeof(int); i++) {
counter += conditions[i]; // Assuming your conditions are 0 or 1.
}
if (counter >= 3) {
// do something
}
新实验:) – 2013-03-19 17:27:54
你可以优化这个代码,在for循环中,if(counter == 3)break;':D – 2013-03-19 17:32:25
@interface Conditions
@property (nonatomic, strong) NSMutableArray *conditions;
- (void) addCondition: (Condition*) theCondition;
- (NSInteger) count;
- (NSInteger) satisfying: (void (^block)(Condition*) );
@end
包裹在一个对象的条件清单。当你需要知道,如果满足这三个条件:
if ([self.conditions satisfying: ^(Condition *c){ return [c isSatisfied]; })>3) {...};
这是矫枉过正 - 也许是可笑的矫枉过正 - 如果这是一个一次性的项目。但是,如果长期维护是一个问题,这将使条件与实施细节脱节。您避免了一长串条件。您可以轻松地添加或更改条件,并且如果其逻辑变得复杂,则可以有一个很好的面向对象的界面来处理它。 (条件可能是作为门面而不是对象操作的协议)。
- 1. 目标C中的条件运算符
- 2. Xcode中的Info.plist文件中的多个图标条目
- 3. 目标C:多个代表
- 4. 多个实例目标c
- 5. SQL中的多个条目?
- 6. 如何删除目标c中的多个标签栏项目?
- 7. 使用多个目标时从C#输出文件名中的目标框架
- 8. 多个目标文件中的C++模板和汇编
- 9. 下载iPhone应用程序中的多个文件(目标c)
- 10. webpack目录中的多个条目
- 11. if条件中的多个条件
- 12. 多个目标 - 多个Settings.bundle文件?
- 13. 动态多个组条目的组件
- 14. C#对象的排名,多个条件
- 15. 如何在Teradata中标记多个条件中的事件
- 16. NSPredicate中的多个条件
- 17. = sum中的多个条件
- 18. Rails中的多个条件
- 19. 项目的参考条件包括有多个条件
- 20. XCode中的多个目标和多个设置配置文件
- 21. 目标C - 只有一个,如果条件工作
- 22. Vapor Xcode项目中的多个目标
- 23. 试图让这个目标条件
- 24. 目标中的多态性C
- 25. iOS目标中的多线程C
- 26. Json文件中的重复条目。 C#
- 27. 定位多个UIImage - 目标C
- 28. 编辑Jabref中的多个条目
- 29. 防止数组中的多个条目
- 30. Rails表单中的多个条目
让我了5秒 – 2013-03-19 17:14:37
非常感谢您为快速和完美的帮助 – user2187565 2013-03-19 17:17:26