[ SWIFT ] - swift 2.0介紹 - 持續更新中 -20151002
本篇主要針對 Swift 2.0 部分進行介紹,內容會持續更新!有興趣的朋友記得常回來喔!
Guard
根據Apple得文件對於Guard得說明如下:
guard 得陳述,就如同if 陳述一樣,依照一個表達式的布林值來執行陳述(statement)。為了讓guard陳述後的程式被執行,你使用一個 guard 陳述來取得必須為真(true)的條件。
一般來說 guard要撘配else來使用,官方建議的方式是用在方法(method)中的return / break / continue 等流程控制中使用,請參考以下範例:
Swift的guard語法非常適合用來做optional的判斷(概念上也可以把guard直接當做 if not 來看)
範例:
if 年齡 >=18 and 年齡 <= 60 {
if 居住地區 in (板橋,土城,中和) {
符合女性疫苗施打
} else {
居住地區不符合
} else {
年齡不符合
}
由上面語法可以發現當有多種情況要判別時,需要透過巢狀 if 得方式來判別並進行處理。
Guard語法:
guard (condition I want to be true) else
{
//return, break, continue, or throw
}
以相同範例為例:
guard (年齡 >=18 and 年齡 <= 60) and (居住地區 in (板橋,土城,中和)) else {
不符合女性疫苗施打條件 }
改用Guard語法,則只需要考慮不符合得狀況進行處理!使語法精簡許多。
println()
早期的 Swift版本中,println() 函數被用來呈現訊息,而在Swift 2.0版本中,In被移除變成print() 來輸出程式中所要顯示的訊息,另外print中參數:appendNewline: false則是表示是否換行,false表示列印時不換行。
例如:print("I Love Swift! I Love Apple!", appendNewline: false)
版本可行性檢查- Availability Check
// Swift 2.0 寫法: 用來檢查API是否符合 iOS9版本
@available(iOS 9, *)
class SuperFancy {
// implementation
}
// Swift 2.0 寫法: 用來檢查API是否符合 iOS8.4 或 OSX10.10版本
guard #available(iOS 8.4, OS X 10.10, *) else {
// what to do if it doesn't meet the minimum OS requirement
return
}
do whlie 改成 repeat whlie
// 原始寫法:var i = 0
print("使用 do-while")
do {
i++
print(i)
} while i < 10
// Swift 2.0 寫法
var i = 0
print("使用 repeat-while")
repeat {
i++
print(i)
} while i < 10
For in where中新增過濾條件
範例:let numbers = [1, 2, 6, 42, 58, 123]
for number in numbers where number > 100 {
print("找出大於100的值" \(number) )
}
新增 IF CASE寫法
if case (_, _, 0..< 7 , _) = userInfo {print("你好,寶寶年齡符合幼兒疫苗施打喔")
} else if case (_, _, _, let email) = userInfo where sex == "" {
print("請輸入性別")
} else if case (_, let name, _, _) = userInfo where birthday != "" {
print("基本資料輸入完畢!")
}

留言
張貼留言
您好:
歡迎到訪我的Blog,這裡有我的生活經驗、美好的回憶和程式開發經驗分享~
目前努力學習Swift中,希望你會喜歡Swift!
如果可以也請你留言給我一個鼓勵喔!
謝謝