for in
- for in 跨度遍历
var a = [1,2,3,4,5,6,7,8,9]
for item in stride(from: 0, to: 8, by: 2){
print(a[item])
}
for item in stride(from: 0, through: 8, by: 2) {
print(a[item])
}
While循环
- while语句是先判断后循环,和其他语言while语句一样。
- repeat while语句是先循环后判断,和其他语言do while语句一样
Switch
- switch语句被增强了,还可以匹配字串,字符,整数,元组,数组等等类型了
- case 后边可以写多个值,并且还可以使用区间
- case:下边必须做处理(这是单一匹配)
- 不用写break语句,它是不存在贯穿想象的。
- 如果匹配到多个case那么会执行第一个匹配到的case,忽略其他case
//多值匹配
var b: Character = "a"
switch b {
case "a","A":
print("a || A")
default:
print("others")
}
//区间匹配
var c = 23
switch c {
case 0..<10:
print("< 10")
case 10..<20:
print("< 20")
case 20..<30:
print("< 30")
default:
print("others")
}
//匹配元组
var a = (0,0)
switch a {
case (_,0):
print("x轴")
case (0,_):
print("y轴")
case (0,0):
print("原点")
default:
print("others")
}
//数组匹配
var temp = [1,2]
switch temp {
case [1,0]:
print("1,0")
case [2,1]:
print("0,1")
case [1,2]:
print("1,2")
default:
print("others")
}
- 值绑定
var a = (2,3)
switch a {
case (let x,0):
print("x 轴:\(x)")
case (0,let y):
print("y 轴:\(y)")
case (let x, let y):
print("x:\(x) y:\(y)")
}
- where条件
var a = (3,-3)
switch a {
case let (x,y) where x == y:
print("x = y")
case let (x,y) where x == -y:
print("x == -y")
case let (x,y):
print("x:\(x) y:\(y)")
}
- 复合匹配
允许用逗号隔开不同的匹配类型,但是只能有相同的类型
符合匹配值绑定中,每个逗号分隔的选项中都要有要绑定的值变量,并且所处位置类型要一致
//复合匹配
let a = "a"
switch a {
case "a", "b", "c", "d",
"e":
print("a - e")
case "A", "B", "C","D",
"E":
print("A - E")
default:
print("others")
}
//复合匹配值绑定
let bc = (3, 4)
switch bc {
case (let x, 3), (3, let x):
print("match")
default:
print("others")
}
控制转移语句
- continue
用在for in中用来结束本次遍历,进入下一次遍历。 - break
用在for in中时候是为了结束整个循环。
用在switch中时候是为了忽略某一个分支 - 贯穿
fallthrough可以贯穿case
var a = "a"
switch a {
case "a":
print("a")
fallthrough
default:
print("default")
}
- 标签
var a = "a"
whileLoop: while a == "a" {
let b = "a"
switch b {
case "a":
print("a")
break whileLoop
default:
print("others")
}
}
- guard语句
如果条件满足有值,就往下执行,如果没值就执行else里代码,并且else里边必须要有结束控制语句
var a = "a"
func test(vale: String?) {
guard let _ = vale else {
print("temp = nil")
return
}
print("vale有值")
}
test(vale: nil)
- 检测API可用性
if #available(iOS 11, *) {
print("iOS11以上")
}else{
print("iOS11以下")
}
总结
结束控制语句
- for in中想要结束当前循环进入下次循环,我们用continue
- for in中想结束整个循环用break
- while中结束循环用break
- switch中忽略分支用break
- 函数中结束向下继续执行用return