Swift 模式匹配中 Where 语句的应用

在 Swift 中,where 语句常与模式匹配结合使用,用于对匹配的模式进行附加条件过滤。

以下示例展示了如何在 switch 语句中使用 where 语句:

let point = (1, 2)

switch point {
case let (x, y) where x == y:
    print("The point is on the line x = y")
case let (x, _) where x < 0>

在上面的代码中,where 语句用于检查匹配的 case 是否满足特定的条件。例如,第一个 case 匹配任何坐标值相同的点,第二个 case 匹配 x 坐标小于 0 的点。

除了 switch 语句,where 语句也可以在 if 语句、for-in 循环和函数参数中与模式匹配一起使用,实现更加灵活的条件判断。

pdf 文件大小:44.72KB