【问题标题】:Is there a way of checking more than one condition in Swift switch?有没有办法在 Swift switch 中检查多个条件?
【发布时间】:2015-08-21 12:06:51
【问题描述】:

在 Swift 中,我需要像这样进行切换:

switch char {
    case "+": statement 1; statement 3
    case "-": statement 2; statement 3
 default: statement 3   
}

但是,我不想复制语句 3,因为它实际上很长,所以我正在寻找另一种方法(如果存在)以某种方式使 switch 检查每个 case 条件,并执行也是默认的。

【问题讨论】:

  • 为什么不在 switch 完成后执行语句 3? (不是在每种情况下)将break 放在默认情况下
  • 谢谢 Okapi,好主意,但实际上我在那个开关中还有一些案例,我选择不写它们以使我的问题更简单和干净

标签: ios swift switch-statement


【解决方案1】:

您可以跳过一个案例并跳过下一个案例以使您恢复默认的唯一方法是重新测试条件:

switch char {
case "+": statement 1; fallthrough
case "-": if char == "-" { statement 2 }; fallthrough
default: statement 3
}

说实话,说实话,这看起来非常节俭。我建议你用函数调用替换你的长语句并保留你上面给出的控制流。

【讨论】:

    【解决方案2】:

    重复代码?局部函数的良好候选者:

    func statement3() {
        // ... lots of stuff here ...
    }
    switch char {
        case "+": statement 1; statement3()
        case "-": statement 2; statement3()
     default: statement3()   
    }
    

    但是如果你真的想要在每一个情况下都做statement3,那么就干脆把它从switch语句中去掉:

    switch char {
        case "+": statement 1
        case "-": statement 2
     default: break   
    }
    statement 3
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-03
      • 1970-01-01
      • 2011-10-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多