If
if
語句最簡單的形式就是只包含一個條件,當且僅當該條件為true
時,才執行相關程式碼:
var price = 30
if price == 30{
print("good price.")
}
// 輸出 "Good price."
if
語句允許二選一,也就是當條件為false
時,執行else 語句:
var price = 30
if price < 30{
print("cheap")
} else {
print("expensive.")
}
// 輸出 "expensive."
if
語句允許多選一,也就是當條件為false
時,執行else 語句:
var price = 90
if price == 30 {
print("cheap")
} else if price == 60 {
print("good price. ")
} else if price == 90 {
print("expensive.")
} else if price == 120 {
print("too expensive.")
}
// 輸出 "expensive."
Switch
switch語句會嘗試把某個值與若干個模式(pattern)進行匹配。根據第一個匹配成功的模式,switch語句會執行對應的程式碼。當有可能的情況較多時,通常用switch語句替換if語句。
var price = 90
switch price{
case 30:
print("cheap")
case 60:
print("good price. ")
case 90:
print("expensive.")
case 120:
print("too expensive.")
default:
print("Price has to be 30, 60, 90, or 120")
}
//輸出:expensive.
*重點:
1. 用Switch語法,最後一定要有default
2. switch還可以用於區間,比if else更靈活:
範例:
var price = 91
switch price{
case 0...30:
print("cheap")
case 31...60:
print("good price. ")
case 61...90:
print("expensive.")
case 91...120:
print("too expensive.")
default:
print("Price has to be 0 to 120")
}
//輸出:too expensive.