小于或大于 Swift switch 语句 [英] Lesser than or greater than in Swift switch statement
本文介绍了小于或大于 Swift switch 语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我熟悉 Swift 中的 switch
语句,但想知道如何用 switch
替换这段代码:
I am familiar with switch
statements in Swift, but wondering how to replace this piece of code with a switch
:
if someVar < 0 {
// do something
} else if someVar == 0 {
// do something else
} else if someVar > 0 {
// etc
}
推荐答案
这是一种方法.假设 someVar
是 Int
或其他 Comparable
,您可以选择将操作数分配给新变量.这使您可以使用 where
关键字以任意方式确定其范围:
Here's one approach. Assuming someVar
is an Int
or other Comparable
, you can optionally assign the operand to a new variable. This lets you scope it however you want using the where
keyword:
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
关键字与范围匹配:
You can also avoid the where
keyword entirely with range matching:
switch someVar {
case Int.min..<0:
print("someVar is \(someVar)")
case 0:
print("someVar is 0")
default:
print("someVar is \(someVar)")
}
这篇关于小于或大于 Swift switch 语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文