for
for
用来遍历数组、字典或者像1...5
这样的区间:
let names = ["Anna", "Alex", "Brain", "Jack"]
for name in names {
print("Hello, \(name)!")
}
如果希望像 C 语言那样从a
遍历到b
,可以用stride()
函数创建一个序列,例如stride(from: a, to: b, by: c)
(不包含b
)或stride(from: a, through: b, by: c)
(包含b
)。
while
如果判断条件为true
,就执行循环,直到判断条件变为false
。
var a = 0
while a < 10 {
print("a = \(a)")
a += 1
}
repeat
会先进行一次循环再判断条件是否为true
,如果是,就继续循环,如果不是就结束循环。
var a = 0
repeat {
print("a = \(a)")
a += 1
} while a < 10
if
if
在判断条件为true
时执行对应的集合,为false
时若有else
就执行else
分支。
let temp = 90
if temp <= 32 {
print("It is cold")
} else if temp >= 86 {
print("It is hot")
} else {
print("It is not cold")
}
可以利用if
来为变量赋值,所有的分支必须都包含相同类型的值。
let temp = 90
let text = if temp <= 32 {
"It is cold"
} else if temp >= 86 {
"It is hot"
} else {
"It is not cold"
}
switch
switch
将给定的值按从上到下的顺序与各case
提供的值依次匹配,当匹配成功时执行该case
对应的分支,如果所有case
都匹配失败就执行default
分支。
let someCharacter: Character = "z"
switch someCharacter {
case "a":
print("The first letter of the alphabet")
case "b", "c":
print("The second or third letter of the alphabet")
case "z":
print("The last letter of the alphabet")
default:
print("Some other character")
}
当某个case
匹配成功时,执行完该分支就会退出,因此不需要显式的break
语句。
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"
}
还可以是一个元组,_
表示可以匹配任何值:
let somePoint = (1, 1)
switch somePoint {
case (0, 0):
print("(0, 0) is at the origin")
case (_, 0):
print("(\(somePoint.0), 0) is on the x-axis")
case (0, _):
print("(0, \(somePoint.1)) is on the y-axis")
case (-2...2, -2...2):
print("(\(somePoint.0), \(somePoint.1)) is inside the box")
default:
print("(\(somePoint.0), \(somePoint.1)) is outside of the box")
}
可以将匹配到的值临时绑定为一个常量或变量,来给分支的函数体使用:
let anotherPoint = (2, 0)
switch anotherPoint {
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))")
}
使用where
检查条件是否成立,如果成立就使用let
创建的x
和y
:
let yetAnotherPoint = (1, -1)
switch yetAnotherPoint {
case let (x, y) where x == y:
print("(\(x), \(y)) is on the line x == y")
case let (x, y) where x == -y:
print("(\(x), \(y)) is on the line x == -y")
case let (x, y):
print("(\(x), \(y)) is just some arbitrary point")
}
控制转移语句
continue
终止本轮循环,立刻开始下一轮循环。break
立即终止当前循环,执行后续的语句。fallthrough
在执行完当前case
对应的语句后继续匹配后面的case
。return
结束当前的函数,返回一个值作为函数的结果。throw
在程序遇到错误时抛出一个错误。