if
語句後面可以跟一個else if
語句,這對於使用單個if ... else if
語句測試各種條件非常有用。
當使用if
,else if
,else
語句時,要記住幾點。
- 一個
if
可以有零個或一個else
語句,它必須在else...if
之後。 if
可以有零或多個else...if
語句,並且它們必須在else
語句之前。- 當有一個
if...else
匹配成功,其餘的else...if
或者else
語句都不會被測試。
語法
Swift 4中if...else if...else
語句的語法如下 -
if boolean_expression_1 {
/* Executes when the boolean expression 1 is true */
} else if boolean_expression_2 {
/* Executes when the boolean expression 2 is true */
} else if boolean_expression_3 {
/* Executes when the boolean expression 3 is true */
} else {
/* Executes when the none of the above condition is true */
}
示例代碼
var varA:Int = 100;
/* 使用if語句檢查布爾條件 */
if varA == 20 {
/* 如果條件為真,則列印以下內容 */
print("varA is equal to than 20");
} else if varA == 50 {
/* 如果條件為真,則列印以下內容 */
print("varA is equal to than 50");
} else {
/* 如果條件為假,則列印以下內容 */
print("None of the values is matching");
}
print("Value of variable varA is \(varA)");
編譯並執行上述代碼時,會產生以下結果 -
None of the values is matching
Value of variable varA is 100