小编典典

小于或大于 Swift switch 语句

all

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

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

阅读 69

收藏
2022-07-30

共1个答案

小编典典

这是一种方法。假设someVar是 anInt或 other
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)")
}
2022-07-30