【问题标题】:Can I programmatically set the condition in a `for` loop?我可以在“for”循环中以编程方式设置条件吗?
【发布时间】:2014-05-22 01:00:44
【问题描述】:

我在for 循环中有大量代码。我想根据布尔变量 countUp 执行 0 到 9 升序或 9 到 0 降序循环。设置初始条件和增量很容易......但是我如何以编程方式设置条件(操作员是问题)?

int startValue = _countUp ? 0 : 9;
int increment = _countUp ? 1 : -1;
// How do I define a condition ??? so that the following single line of code will work:

for (int i = startValue; ???; i = i + increment) {
  ...

我尝试了一个 NSString,当然没有用。我知道有一些解决方案将两个循环都放在 if-else 语句中,即将循环代码定义为函数,并使用升序或降序 for 循环调用它。但是有没有一种优雅的方式来以编程方式设置for 循环?

【问题讨论】:

  • 这里有多个好答案;希望我能记下不止一个。我将最终实现 Bryan 的第二个解决方案,但 RobP 遇到了关于有条件地定义条件的主要问题。

标签: ios for-loop conditional-statements


【解决方案1】:

我只想在 for 循环中实现三元运算符。

for (int i = _countUp ? 0 : 9; i != _countUp ? 9 : 0; i += _countUp ? 1 : -1) {

}

【讨论】:

    【解决方案2】:

    如何使用三元运算符?它简洁易读,应该可以解决问题。

    for(int i = startValue; _countUp ? (i <= 9) : (i >=0); i = i + increment) {
    

    【讨论】:

    • +1 用于直接回答问题,并按照 OP 的要求使用正确的运算符。
    • 谢谢,就这样。只是出于好奇,什么类型的变量是(i
    • 它是布尔值,一个真或假值。任何if() 的 () 中的条件都需要计算为布尔值,A ? B : C 中的 A 处的条件也需要计算为布尔值。
    【解决方案3】:

    一种方法是添加endValue

    int startValue = _countUp ? 0 : 9;
    int increment = _countUp ? 1 : -1;
    int endValue = _countUp ? 9 : 0;
    
    for (int i = startValue; i != endValue; i = i + increment) {
    
    }
    

    或者更简单

    for (int i = 0; i < 10; i++) {
        int value = _countUp ? i : 9 - i;
        // use value
    }
    

    【讨论】:

      猜你喜欢
      • 2021-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-24
      • 2021-06-13
      • 1970-01-01
      • 2021-02-05
      • 1970-01-01
      相关资源
      最近更新 更多