我熟悉switchSwift中的语句,但想知道如何用来替换这段代码switch:
switch
if someVar < 0 { // do something } else if someVar == 0 { // do something else } else if someVar > 0 { // etc }
这是一种方法。假设someVar是Int或其他Comparable,则可以选择将操作数分配给新变量。这样,您就可以使用where关键字来对其进行范围划分:
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)") }