Swift - if...else if...else 語句



一個if語句後面可以跟著一個可選的else if...else語句,這在使用單個if...else if語句測試各種條件時非常有用。或者我們可以說,if… else if…else語句允許你按順序檢查多個條件。

它建立了一個決策樹,其中每個條件都按順序進行評估,第一個為真的條件的語句塊將被執行。如果沒有任何條件為真,則 else 部分將被執行。if…else if…else 語句也稱為 if… else 階梯。

使用if、else if 和 else語句時,需要記住以下幾點。

  • 一個if可以有零個或一個 else,並且它必須出現在任何 else if 之後。

  • 一個if可以有零到多個 else if,並且它們必須出現在 else 之前。

  • 一旦一個else if成功,則不會測試任何剩餘的else ifelse

語法

以下是 if…else if…else 語句的語法:

if boolean_expression1{ 
   /* Execute when the boolean expression 1 is true */
}
else if boolean_expression2{
   /*Execute when the boolean expression 2 is true*/
}
else if boolean_expression3{
   /*Execute when the boolean expression 3 is true*/
}else{
   /* Execure when none of the above conditions is true */
}

流程圖

下面的流程圖將展示 if…else if…else 語句的工作原理。

if...else if...else Statement

示例

Swift 程式演示if… else if…else語句的使用。

import Foundation
var varA:Int = 100;

/* Check the boolean condition using the if statement */
if varA == 20 {

   /* If the condition is true then print the following */
   print("varA is equal to than 20");

} else if varA == 50 {

   /* If the condition is true then print the following */
   print("varA is equal to than 50");

} else {

   /* If the condition is false then print the following */
   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

示例

Swift 程式使用if…else階梯檢查當前季節。

import Foundation

let myMonth = 5

// Checking Season using if...else ladder
if myMonth >= 3 && myMonth <= 5 {
   print("Current Season is Spring")
} else if myMonth >= 6 && myMonth <= 8 {
   print("Current Season is Summer")
} else if myMonth >= 9 && myMonth <= 11 {
   print("Current Season is Autumn")
} else {
   print("Current Season is Winter")
}

輸出

它將產生以下輸出:

Current Season is Spring

示例

Swift 程式使用 if…else if…else 語句計算學生的成績。

import Foundation

let marks = 89

// Determine the grade of the student
if marks >= 90 {
   print("Grade A")
} else if marks >= 80 {
   print("Grade B")
} else if marks >= 70 {
   print("Grade C")
} else if marks >= 60 {
   print("Grade D")
} else {
   print("Grade F")
}

輸出

它將產生以下輸出:

Grade B
廣告