swift 牛逼的地方,改动很牛的地方 switch 语法

不用再写break,匹配到就返回

不再有之前的case 穿透 但是可以逗号分割,但是每一个case的函数体必须要包含至少一个可执行的语句

在一个switch的case中匹配多个值可以用逗号分割,并且可以写成多行

 

//: A UIKit based Playground for presenting user interface

import UIKit
let a:Character = "a"
switch a {
case "a","A":
    print("the letter A or a")
default:
        print("the letter other")

}

switch 的case 的值可以在一个区间中匹配

//: A UIKit based Playground for presenting user interface

import UIKit

let approximateCount = 62
let countedThings = "moons orbiting Saturn"
var natrualCount:String
switch approximateCount {
case 0:
    natrualCount = "no"
case 1..<5:
    natrualCount = "a few"
    case 5..<12:
    natrualCount = "several"
    case 12..<100:
    natrualCount = "donzens of"
    case 100..<1000:
    natrualCount = "hundreds of"

default:
    natrualCount = "Manyy"
}

元祖匹配

你可以用元祖在一个switch 语句中测试多个值

使用下划线(_)来表示所有可能的值

code

//: A UIKit based Playground for presenting user interface

import UIKit

let somePoint=(1,1)
switch somePoint {
case (0,0):
    print("is at the origin")
    case (_,0):
        print("(\(somePoint.0),0)is on the x-axis")
    case (0,_):
        print("0,(\(somePoint.0))is on the Y-axis")
    
    
case (-2...2,-2...2):
         print("(\(somePoint.0),\(somePoint.1)) is inside  the box")
default:
    print("(\(somePoint.0),\(somePoint.1)) is outside of the box")
}

(1,1) is inside  the box

这可以理解为一个方框4*4的方框 -2...2

值绑定

siwtch 和case 可以将匹配到的值临时绑定为一个常量或者变量。来给case的函数体使用

如果使用var 关键字 ,临时的遍历就会以和值的值来创建并初始化,对这个遍历的任何改变都智慧在case的函数体内有效

code

//: A UIKit based Playground for presenting user interface

import UIKit

let somePoint=(2,0)
switch somePoint {
case (let x,0):
    print("on the x axis with an x value of \(x)")
    case (0,let y):
         print("on the y-axis with an x value of \(y)")
    case (let x, let y):
        print("somewhere else at (\(x),\(y))")
    
    
    
}

somewhere else at (2,0)

更牛逼的可以添加where

可能工程师觉得where还是不够强大。

于是乎。。。

switch case 可以使用where分句来检索是否符合特定的约束

//: A UIKit based Playground for presenting user interface

import UIKit

let somePoint=(2,-2)
switch somePoint {

    case let(x,y) where x==y :
        print("(\(x),\(y))is on the line x == y")
    
    case let(x,y) where x == -y:
     print("(\(x),\(y))is on the line x == -y")
    
case let(x,y):
    print("(\(x),\(y))is just some arbitrary point")
}

(2,-2)is on the line x == -y

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

安果移不动

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值