小于或大于在Swift switch语句中

前端之家收集整理的这篇文章主要介绍了小于或大于在Swift switch语句中前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我熟悉Swift中的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)")
}
原文链接:https://www.f2er.com/swift/321252.html

猜你在找的Swift相关文章