// switch必须要保证能处理所有情况 case、default后面至少要有一条语句 如果不想做任何事,加个break即可,fallthrough是贯穿当前判断
var num = 1
num = Int(arc4random())
switch num {
case 1:
print("1")
case 2:
print("2")
case 3:
break
case 4:
print("4")
case 5:
print("5")
fallthrough
case 6:
print("5 or 6")
default:
print("other \(num)")
}
//如果能保证已处理所有情况,也可以不必使用default
enum Answer { case right, wrong }
let answer = Answer.right
switch answer {
case Answer.right:
print("right")
case Answer.wrong:
print("wrong")
}
// 由于已确定answer是Ansewer类型,因此可以省略Answer
switch answer {
case .right:
print("right")
case .wrong:
print("wrong")
}
//复合条件
// switch也支持Character、String类型
let string = "Jack"
switch string {
case "Jack":
fallthrough
case "Rose":
print("Right person")
default:
break
} // Right person
let character: Character = "a"
switch character {
case "a", "A":
print("The letter A")
default:
print("Not the letter A")
} // The letter A
switch string {
case "Jack", "Rose":
print("Right person")
default:
break
} // Right person
// 区间匹配
let count = 62
switch count {
case 0:
print("none")
case 1..<5:
print("a few")
case 5..<12:
print("several")
case 12..<100:
print("dozens of")
case 100..<1000:
print("hundreds of")
default:
print("many")
} // dozens of
// 元组匹配
let point = (1, 1)
switch point {
case (0, 0):
print("the origin")
case (_, 0):
print("on the x-axis")
case (0, _):
print("on the y-axis")
case (-2...2, -2...2):
print("inside the box")
default:
print("outside of the box") } // inside the box
//可以使用下划线 _ 忽略某个值
//关于case匹配问题,属于模式匹配(Pattern Matching)的范畴,以后会再次详细展开讲解
//值绑定
let point2 = (2, 0)
switch point2 {
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 a y value of \(y)")
case let (x, y):
print("somewhere else at (\(x), \(y))")
} // on the x-axis with an x value of 2
//必要时let也可以改为var
// where
let point3 = (1, -1)
switch point3 {
case let (x, y) where x == y:
print("on the line x == y")
case let (x, y) where x == -y:
print("on the line x == -y")
case let (x, y):
print("(\(x), \(y)) is just some arbitrary point")
} // on the line x == -y
// 将所有正数加起来
let numbers = [10, 20, -10, -20, 30, -30]
var sum = 0
for num in numbers where num > 0 { // 使用where来过滤num
sum += num
}
print(sum) // 60
// 标签语句
outer: for i in 1...4 {
for k in 1...4 {
if k == 3 {
continue outer
}
if i == 3 {
break outer
}
print("i == \(i), k == \(k)")
}
}
网友评论