Swift编程

更加强大的 switch

2020-01-20  本文已影响0人  码农UP2U

switch

没有隐式贯穿

区间匹配

元组匹配

值绑定

where 子句

复合匹配

复合绑定 - 值绑定

复合匹配同样可以包含值绑定。所有复合匹配的模式都必须包含相同的值绑定集合,并且复合情况中的每一个绑定都得有相同的类型格式。这才能确保无论复合匹配的那部分命中了,接下来的函数体中的代码都能访问到绑定的值并且值的类型也都相同。

代码示例
let char: Character = "z"

// 该 switch 输出 the last letter of alphabet
switch char {
case "a":
    print("the first letter of alphabet")
case "z":
    print("the last letter of alphabet")
    // 注释掉 default 会报错
    // 报错提示在 switch 行,报错内容为 “Switch must be exhaustive”
default:
    print("other letter")
}

// 该 switch 输出 the last letter of alphabet
switch char {
    // 复合匹配
case "a", "A":
    print("the first letter of alphabet")
case "z":
    print("the last letter of alphabet")
default:
    print("other letter")
}

// 区间匹配
let count = 62
var naturalCount: String

switch count {
case 0:
    naturalCount = "none"
case 1..<12:
    naturalCount = "a free"
case 12..<100:
    naturalCount = "dozens of"
case 100..<1000:
    naturalCount = "hundreds of"
default:
    naturalCount = "many"
}

// 输出 dozens of
print(naturalCount)


// 元组匹配
let somePoint = (1, 1)

// 输出 point in box
switch somePoint {
case (0, 0):
    print("point at origin")
// 元组匹配的值绑定
case (let x, 0):
    print("point at x-axis, distance is \(x)")
case (0, _):
    print("point at y-axix")
case (-2...2, -2...2):
    print("point in box")
// 增加限定条件
case let (x, y) where x == y:
    print("x = y")
default:
    print("point at other palce")
}


我的微信公众号:“码农UP2U”
上一篇 下一篇

猜你喜欢

热点阅读