前言
- Swift switch 语句中,默认语法是必须要添加 default 语句。
- Swift Switch 语句中, break 是可以省略不写的,默认执行完当前 case 下的内容后,直接返回了,即使后续还有可满足的条件。
基础用法
let someChar: Character = "z"
switch someChar {
case "a":
print("this is a ")
case "b":
print("this is b")
case "z":
print("this is z")
default:
print("this is else ")
}
输出结果
this is z
复合匹配
复合匹配就是 同一个 Case 下的多个条件
这里的多个条件就是 ,可能是 a,或者 b ,任何一个条件匹配了,那么就被认为当前条件满足。
let someChar: Character = "Z"
switch someChar {
case "a":
print("this is a ")
case "z","Z":
print("this is z")
default:
print("this is else ")
}
输出结果
this is z
区间匹配
被判断的值要满足 case 语句的区间条件
let count = 20
var resultValue = ""
switch count {
case 0:
resultValue = "none"
case 1..<12:
resultValue = "a few"
case 12..<100:
resultValue = "dozens of"
case 100..<1000:
resultValue = "hundreds of"
default:
resultValue = "many"
}
print(resultValue)
输出结果
dozens of
元组匹配
let somePoint = (1,1)
switch somePoint {
case (0, 0):
print("point at origin")
case (_, 0): //下划线表示可以是任意值,这里的条件是只需要满足第二个值0
print("point at x-axis")
case (0, _): // 下划线表示可以是任意值,这里的条件是只需要满足第一个是0
print("point at y-axis")
case (-2...2, -2...2):
print("point is box")
default:
print("point at other place")
}
输出结果
point is box
值绑定
let somePoint = (1,0)
switch somePoint {
case (0, 0):
print("point at origin")
case (let x, 0): // 当前条件只需要满足第二个值是0, 并且可以引用 x 来获取第一位的值,
print("point at x-axis , distance is \(x)")
case (0, let y): // 当前条件只需要满足第一个值是0, 并且可以引用 x 来获取第二位的值,
print("point at y-axis, distance is \(y)")
case (-2...2, -2...2):
print("point is box")
default:
print("point at other place")
}
输出结果
point at x-axis , distance is 1
where 语句
switch case 可以使用 where 分句来检查是否符合特定的约束
let point = (1,2)
switch point {
case (0, 0):
print("---- 0, 0")
case (let x, let y) where y == 2:
print("second value = 2")
default:
print("other value")
}
输出结果
second value = 2
复合匹配-值绑定
let value = (9, 0)
switch value {
case (let v, 0), (0, let v):
print("value is \(v)")
default:
print("not value")
}
网友评论