Control Transfer Statements
Control transfer可以在程式執行的時候改變順序。Swift提供了四種語法:
1. continue
2. break
3. fallthrough
4. return (會在Functions這一章說明)
Continue
continue會讓迴圈停下來並且開始下一輪的迴圈。
Break
break一樣也是讓迴圈停下來,但迴圈也會結束執行。
FallThrough
在Swift裡,switch會在完成第一次判定後結束,不需要寫break;意即若接下來有符合case裡的條件,一樣不會執行;若我們需要經過所有可能成立的條件,可以在statements最後加一行fallthrough,意即我們需要繼續跑switch case:
let intToDescribe = 5
var description = "The number \(intToDescribe) is"
switch intToDescribe {
case 2, 3, 5, 7, 11, 13, 17, 19:
description += "a prime number"
fallthrough
default:
description += ", and also an integer."
}
上面的例子,若是沒有加上fallthrough,就不會再往下判斷,description就只有"The number 5 is a prime number"。
加上去之後,default也會成立(default不論statement是什麼都會成立),description就會是"The number 5 is a prime number, and also an integer."
要注意一點,若是將fallthrough放到statements中間,那麼在fallthrough以下的都不會執行喔。
Early Exit
Swift是供了"guard"的statement,他的用法跟if很類似,不過他處理的情況是"空值"的時候要做的事:
var person = ["name": "John"]
guard let myName = person["name"] else {
print("not exist name key")
}
上面的例子會在宣告myName的時候直接判斷是否存在name這個key,並直接處理不存在時要做的事;通常我們會在函數裡使用這種方法,可以很快的確認傳進來的參數是否有我們要用的東西。
Checking API Availability
Swift提供了內建的api版本檢查機制,可以在分別針對新舊版本做處理:
if #available(platform name version, ..., *) {
statements to execute if the APIs are available
} else {
fallback statements to execute if the APIs are unabailable
}
比如說,UIAlertController是在iOS8以後才提供的方法,在之前的話都是用UIAlertView或是UIActionSheet,就可以用此來做判別:
if #available(iOS 8, *) {
// Use UIAlertController
} else {
// Use UIAlertView or UIActionSheet
}