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

Swift语法基础:18 - Swift的元组, 绑定值, Where

发布时间:2020-12-14 02:19:23 所属栏目:百科 来源:网络整理
导读:好了,下面让我们继续往下看吧: 1.元组 你可以使用元组在同一个 switch 语句中测试多个值。元组中的元素可以是值,也可以是范围。另外,使用下划线( _ )来匹配所有可能的值。 let somePoint = (1 , 1 ) switch somePoint { case (0 , 0 ): println ( "(0,0)is a

好了,下面让我们继续往下看吧:


1.元组

你可以使用元组在同一个 switch 语句中测试多个值。元组中的元素可以是值,也可以是范围。另外,使用下划线( _ )来匹配所有可能的值。

let somePoint = (1, 1)
switch somePoint {
case (0, 0):
    println("(0,0)is at the origin")
case (_, 0):
    println("((somePoint.0),0) is on the x-axis")
case (0,_):
    println("0,(somePoint.1) is on the y-axis")
case (-2...2, -2...2):
    println("((somePoint.0),(somePoint.1)) is inside the box")
default:
    println("((somePoint.0),(somePoint.1)) is outside of the box")
}
//打印出来的结果: (1,1) is inside the box

2.绑定值

case 块的模式允许将匹配的值绑定到一个临时的常量或变量,这些常量或变量在该 case 块 里就可以被引用了——这种行为被称为值绑定。

let anotherPoint = (2,0)

switch anotherPoint {
case (let x,0):
    println("on the x-axis with an x value of (x)")
case (0,let y):
    println("on the y-axis with a y value of (y)")
case let (x,y):
    println("somewhere else at ((x),(y))")
}
// 打印出来的结果: on the x-axis with an x value of 2

3.Where

case 块的模式可以使用 where 语句来判断额外的条件。当且仅当 where 语句的条件为真时,匹配到的 case 块才会被执行。

let yetAnotherPoint = (1,-1)

switch yetAnotherPoint {
    case let (x,y) where x == y:
        println("((x),(y)) is on the line x == y")

    case let (x,y) where x == -y:
        println("((x),(y)) is on the line x == -y")

    case let (x,y):
        println("((x),(y)) is just some arbitrary point")
}
// 打印出来的结果: (1,-1) is on the line x == -y

好了,这次就讲到这里,下次我们继续~

(编辑:李大同)

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

    推荐文章
      热点阅读