005-Swift3.0之控制语句
一、循环语句
1.for-in循环
1)遍历区间操作符
for index in 1...5 { let value = index * 5 print("\(index) * 5 = \(value)") }
2)使用下划线忽略每一项的值
let a = 3 let n = 10 var sum = 0 for _ in 1...n { sum += a }
3)遍历数组
let names = ["Frank0", "Frank1", "Frank2", "Frank3", "Frank4", "Frank5",] for name in names { print(name) }
4)遍历字典
let students = ["0": "Frank0", "1": "Frank1", "2": "Frank2", "3": "Frank3"] for (id, name) in students { print("学号:\(id),姓名:\(name)") }
2.while循环
var p = 0 while p < 3 { print(p) p += 1 }
3.repeat-while
var q = 0 repeat { print(q) q += 1 } while q < 3
二、条件判断语句
1.if语句
let x = 10 let y = 2 if x < y { print("x < y") } else if x == y { print("x = y") } else { print("x > y") }
2.switch语句
1)case匹配多个值
let someCharacter: Character = "c" switch someCharacter { case "a": print("The first letter of the alphabet") case "b", "c", "d": print(someCharacter) case "z": print("The last letter of the alphabet") default: print("Some other character") }
2)case匹配区间
let approximateCount = 62 let countedThings = "moons orbiting Saturn" var naturalCount: String switch approximateCount { case 0: naturalCount = "no" case 1..<5: naturalCount = "a few" case 5..<12: naturalCount = "several" case 12..<100: naturalCount = "dozens of" case 100..<1000: naturalCount = "hundreds of" default: naturalCount = "many" }
3)case匹配元祖
let somePoint = (1, 1) switch somePoint { case (0, 0): print("somePoint在坐标原点上") case (_, 0): print("somePoint在x轴上") case (0, _): print("somePoint在y轴上") case (-2...2, -2...2): print("somePoint在以坐标原点为圆心,上下左右延伸2个坐标范围内") default: print("somePoint在其他区域") }
4)case匹配值绑定
let anotherPoint = (2, 0) switch anotherPoint { case (let x, 0): print("anotherPoint在x轴上,x = \(x)") case (0, let y): print("anotherPoint在y轴上,y = \(y)") case let (x, y): print("anotherPoint在象限内,x = \(x),y = \(y)") }
5)case中使用关键字where添加额外判断条件
let yetAnotherPoint = (1, -1) switch yetAnotherPoint { case let (x, y) where x == y: print("yetAnotherPoint在直线y=x上,x = \(x),y = \(y)") case let (x, y) where x == -y: print("yetAnotherPoint在直线y=-x上,x = \(x),y = \(y)") case let (x, y): print("yetAnotherPoint在其他直线上,x = \(x),y = \(y)") }
三、控制转移语句
1.continue 退出本次循环
2.break 退出循环
3.fallthrough 贯穿
let scroe = 90 switch scroe { case 0...59: print("不及格") case 60...100: print("及格") fallthrough // 匹配到当前case后,会继续往下匹配 case 80...100: print("高分") default: print("其他") }
4.return 提前退出
5.throw

浙公网安备 33010602011771号