我熟悉 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/