// 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)")
}
}
笔记02 swift 流程控制
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 参考资料:《JavaScript从入门到精通》、《PHP、MySQL与JavaScript学习手册》 赋值语句 赋...
- HTML 学习笔记 May 9,2017 js运行原理、js开发工具介绍、js程序(hello)、js基本语法、j...