for-in循環(huán)
for-in循環(huán)與c++的for循環(huán)有些相像,但沒有更新循環(huán)控制變量的處理。
let numberOfLegs = [“spider”: 8, “ant”: 6, “cat”: 4]
for (animalName, legCount) in numberOfLegs {
Statement
}? //for-in循環(huán)遍歷字典
while循環(huán),repeat-while循環(huán)
while condition {
Statement
}
repeat {
Statement
} while condition
其中repeat-while循環(huán)與c++的do-while循環(huán)類似。
switch
與c++不同,swift的switch語句不會(huì)貫穿,不需要每個(gè)case都加上break,除非有意如此,在需要貫穿特性的case分支后加fallthrough,表示貫穿到下一分支。
swift的switch語句比c++的switch靈活得多。可以多個(gè)條件組合成一個(gè)case分支,用逗號(hào)“,”分開;case分支還可以區(qū)間匹配,
switch someCondition {
Case 0:
Case 1..<5:
Case 5…10:
}
元組匹配,
switch someCondition {
Case (0, 0):
Case (0, _):
Case (_, 0):
case (-2…2, -2…2):
Default:
}
還可以用where添加額外的條件,
Switch point {
Case let (x, y) where x == y:
Case let (x, y) where x == -y:
Case let (x, y):
}
另外,swift還添加了c++沒有的guard語句,用于提前退出,當(dāng)然c++可以通過if語句來實(shí)現(xiàn)。guard語句的用法如下,
func greet(person: [String: String]) {
guard let name = person[“name”] else {
return
}
}