swift 循环控制
swift 里主要就是for in 和 while 循环。 repeat while。
let nameArray = [1,3,2,4,5]
for value in nameArray {
print(value)
}
for _ in nameArray {
print("当我不需要知道具体值时,可以这样写")
}
let tuple = ["cat" : 4, "spider" : 8, "maomaochong" : 20]
for value in tuple {
print("\(value.key) has \(value.value) legs")
}
for (name, value) in tuple {
print("\(name) has \(value) legss")
}
//跳步遍历
for index in stride(from: 0, to: 45, by: 5) {
print(index)
}
强大的switch 语句
switch 必须有一个默认匹配default。 并且没有隐式贯穿,所以不用写break。
switch 匹配方式有很多种: 区间匹配, 多值匹配,元组匹配,复合匹配,还可以值绑定,还可以加where语句。
//必须要用default分支。 不用加break,不会隐式贯穿。 可以是单表达式,也可以是多个,区间判断
let type: Character = "c"
switch type {
case "a","e","i","o","u":
print("原因字母")
case "b"..<"e":
print("开头几个字母")
case "K":
print("你就是大写deK")
default:
print("其它字母")
}
//上面一个满足了,下面case即使满足也不执行了
let point = (-1, -1)
switch point {
case (0, 0):
print("原点")
case (_, 0):
print("在X轴上")
case (-2...2, -2...2):
print("在正方形内")
// fallthrough //这里使用fallthrough会报错 error: 'fallthrough' cannot transfer control to a case label that declares variables。因为:fallthrough后一个case条件里不允许定义常量/变量 除了紧跟着的后一个,后面的其他case还是可以定义常量/变量的
case (let x, 0):
print("\(x) 设置值,y = 0")
case (0, let y):
print("x==0, y = \(y)")
case (let x, let y) where x == y:
print("X == Y")
case (_, let y) where y == 3:
print("当x为随意值,y == 3")
default:
print("other")
}
循环控制语句: continue:结束本次循环,进行下一次循环。 break:跳出当前循环, 到}结束位置。 fallthrough:贯穿。语句标签。
let num = 5
var description = "the num : \(num) is "
switch num {
case 2, 3, 3, 5, 7: //这里有重复的case 也可以的。
description += "a primer"
fallthrough //可以贯穿到下面case执行
case 3 + 2:
description += " 来了老弟";
fallthrough
default:
description += ";alse a inter"
}
print(description)
循环标签举例: 可以测试下不加标签打印结果对比下。
//添加循环标签可以按我们要求跳出循环,但是不建议烂使用,否则代码难以理解
var num = 10
bigLoop: while num > 0 { //循环标签bigLoop
switch num {
case 9:
print("num == 9")
case 10:
var sum = 0
for i in 0...10 {
sum += i
if i == 9 {
print(sum)
break bigLoop //跳出标记的循环
}
}
default:
print("default")
}
num -= 1
}
guard 语句表达式
//当guard 跟着的表达式为false,才会执行else表达式。 guard语句必须跟着一个else。 使用guard语句,很容易遵循”黄金大道“code法则。
guard statement else {
//表达式
}
检查API:
if #available(iOS 13, *) {
print("iOS 13 以上系统API")
} else {
print("iOS 13 以下系统API")
}
网友评论