微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐