-
For循環(huán)
- for-in
let base = 3
let power = 10
var answer = 1
for _ in 1...power {
answer *= base
}
print("(base) to the power of (power) is (answer)") - for 循環(huán)
傳統(tǒng)的for循環(huán)在swift3.0被取消;i++,++i被取消展哭;
新的形式:for index in 0..<3 { }
等價于以前的 for (int index = 0; index < 3; index++){ }
- for-in
-
While循環(huán)
- while循環(huán)闻蛀,每次在循環(huán)開始時計算條件是否符合您市;
- repeat-while循環(huán),每次在循環(huán)結(jié)束時計算條件是否符合薪棒。與do-while類似
-
條件語句
if
-
switch
與OC不同榕莺,在swift中,不存在隱式的貫穿钉鸯,當(dāng)匹配的case分支中的代碼執(zhí)行完畢后,程序會終止swift語句扣蜻,而不會繼續(xù)執(zhí)行下一個case分支及塘。即不需要在case分支中顯式的使用break語句。好處是語句更安全芳肌、更易用。 如果想要貫穿至特定的case分支中亿笤,請使用fallthrough語句栋猖。
-
控制轉(zhuǎn)移語句
-
continue
告訴一個循環(huán)體立刻停止本次循環(huán)迭代,重新開始下次循環(huán)迭代肃拜。注意:在一個帶有條件和遞增的for循環(huán)體中,調(diào)用continue語句后燃领,迭代增量仍然會被計算求值锦援。循環(huán)體繼續(xù)像往常一樣工作,僅僅只是循環(huán)體中的執(zhí)行代碼會被跳出。
let puzzleInput = "great minds think alike"
var puzzleOutput = ""
for character in puzzleInput.characters {
switch character {
case"a", "e", "i", "o", "u", " ":
continue
case"b":
break
default:
puzzleOutput.append(character)
}
}print(puzzleOutput)
-
輸出:
grtmndsthnklk
break
會立刻結(jié)束整個控制流的執(zhí)行区岗。在swift語句中躏尉,你可以使用break來忽略某個分支。fall through
此關(guān)鍵字 不會檢查它下一個將會落入執(zhí)行的case中的匹配條件。
let integerToDescribe = 2
var description = "the number (integerToDescribe) is"
switch integerToDescribe {
case 2, 3, 5, 7, 11, 13, 17, 19:
description += "a prime number, and also"
fallthrough
default:
description += " an integer"
}
print(description)
輸出:
the number 2 is a prime number, and also an integer
帶標(biāo)簽的語句:
label name: while condition { statements }
同樣的規(guī)則適用于所有的循環(huán)體和switch代碼塊蒂誉。return
throw
-
提前退出
像if語句一樣,guard 的執(zhí)行取決于一個表達(dá)式的布爾值右锨。我們可以用來要求條件必須為真時碌秸,以執(zhí)行g(shù)uard語句后的代碼。
不同于if語句蹂窖,一個guard語句總是有一個else分句,如果條件不為真則執(zhí)行else分句中的代碼瞬测。
如果條件不滿足纠炮,在else分支上的代碼就會被執(zhí)行。這個分支必須轉(zhuǎn)移控制以退出guard語句出現(xiàn)的代碼段孝宗,它可以用return,break,continue ,throw,或者調(diào)用一個不返回的方法或函數(shù),例如:fatalError()因妇。
-
對比if語句看疗,按需使用guard語句會提升代碼的可靠性。它可以使代碼連貫的被執(zhí)行而不需要將它包在else塊中两芳,它可以使你處理違反要求的代碼使其接近要求。
func greet(person: [String: String]){
guard let name = person["name"] else {return}
print("hello (name)")
guard let location = person["location"] else {
print("i hope the weather is nice near you.")
return
}
print("i hope the weather is nice in (location)")}greet(person: ["name": "john"]) greet(person: ["name": "jane", "location": "ShangHai"])
輸出:
hello john
i hope the weather is nice near you.
hello jane
i hope the weather is nice in ShangHai
-
檢測API可用性
swift有檢查API可用性的內(nèi)置支持是复。