swift之switch续(元组,值绑定,where)

本文深入探讨Swift编程中的`switch`语句,重点讲解如何匹配元组,使用值绑定提升代码可读性,并结合`where`子句进行更精确的条件判断。通过实例解析,帮助开发者更好地理解和应用这些高级特性。
摘要由CSDN通过智能技术生成



import Foundation

let point = (2, 2)
switch point {
    case (0, 0):
        print("point is (0, 0)")
    case (_, 0): //_匹配所有可能的值
        print("point is (_, 0)")
    case (0, _):
        print("point is (0, _)")
    case (0...3, 0...3):
        print("point is the scope of (0...3, 0...3)")
    default:
        print("not in the scope of ... ")
}

//值绑定
//case 分⽀的模式允许将匹配的值绑定到⼀个临时的常量或变量,这些常量或变量在该
//case 分⽀⾥就可以被引⽤了——这种⾏为被称为值绑定(value binding)。
let anotherPoint = (2, 0)
switch anotherPoint {
    case (let x, 0): //匹配纵坐标是0的点,并将横坐标的值赋予x,下同
        print("on the x-axis with an x value of \(x)")
    case (0, let y):
        print("on the y-axis with a y value of \(y)")
    case let (x, y): //匹配所有
        print("somewhere else at (\(x), \(y))")
}


//case分支的模式可以使用where语句来判断额外的条件
let yetAnotherPoint = (1, -1)
sw
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值