加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

小于或大于在Swift switch语句中

发布时间:2020-12-14 06:08:16 所属栏目:百科 来源:网络整理
导读:我熟悉Swift中的switch语句,但想知道如何用开关替换这段代码: if someVar 0 { // do something} else if someVar == 0 { // do something else} else if someVar 0 { // etc} 这里有一种方法。假设someVar是Int或其他Comparable,您可以选择将操作数分配给
我熟悉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)")
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读