swift - 小于或大于 Swift switch 语句

标签 swift switch-statement

我熟悉 Swift 中的 switch 语句,但想知道如何用 switch 替换这段代码:

if someVar < 0 {
    // do something
} else if someVar == 0 {
    // do something else
} else if someVar > 0 {
    // etc
}

最佳答案

这是一种方法。假设 someVar 是一个 Int 或其他 Comparable,您可以选择将操作数分配给一个新变量。这使您可以使用 where 关键字来限制范围:

var someVar = 3

switch someVar {
case let x where x < 0:
    print("x is \(x)")
case let x where x == 0:
    print("x is \(x)")
case let x where x > 0:
    print("x is \(x)")
default:
    print("this is impossible")
}

这可以稍微简化一下:

switch someVar {
case _ where someVar < 0:
    print("someVar is \(someVar)")
case 0:
    print("someVar is 0")
case _ where someVar > 0:
    print("someVar is \(someVar)")
default:
    print("this is impossible")
}

您还可以通过范围匹配完全避免 where 关键字:

switch someVar {
case Int.min..<0:
    print("someVar is \(someVar)")
case 0:
    print("someVar is 0")
default:
    print("someVar is \(someVar)")
}

关于swift - 小于或大于 Swift switch 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31656642/

相关文章:

xcode - 快速关闭 : Cannot convert value of type '(_) -> Bool' to expected argument type

ios - 以编程方式根据 subview (标签)创建具有大小的 UIView

java - 如何匹配 switch 语句中的正则表达式?

javascript for...in + if-test(在表单内的开关内部)

string - 如何将很长的案例模式拆分成多行?

ios - 文本上的操作标签

ios - Pod安装耗时长安装不上

swift - 当我以编程方式从 Storyboard 加载窗口时,为什么在 NSView 中未调用 drawRect?

java - 我怎样才能让这个 switch 语句使用扫描仪工作?

swift - 在分段控制开关中加载UICollectionViewController