• Swift语法基础:18


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


    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

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

  • 相关阅读:
    Mac挂载分区
    连接SFTP命令
    【转】10.13.6蓝牙失效的解决方法(Broadcom-BCM94352z-DW1560)
    Jetbrains2020系列配置路径变动(Pycharm2020双击无法打开)
    libtorch 常用api函数示例(史上最全、最详细)
    有用链接
    cuda 编程1
    CMakeLists.txt
    模型压缩--剪枝,tensorrt实验调研
    iou map TP TN FP FN Precision Recall
  • 原文地址:https://www.cnblogs.com/iOSCain/p/4529371.html
Copyright © 2020-2023  润新知