Swift - if...else 語句



if-else 語句允許根據給定的表示式執行不同的程式碼塊。如果給定的條件為真,則 if 語句內的程式碼將執行;如果給定的條件為假,則 else 語句內的程式碼將執行。

或者我們可以說,if-else 語句是 if 語句的修改版本,其中 if 語句可以後跟一個可選的 else 語句,當布林表示式為假時執行。

例如,小明要去市場,他媽媽告訴他,如果發現蘋果打折就買蘋果,否則就買葡萄。這裡的 if 條件是“蘋果打折”,else 條件是“買葡萄”。因此,小明只有在 if 條件為真時才會買蘋果,否則他會買葡萄。

語法

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

if boolean_expression{ 
   /* statement(s) will execute if the boolean expression is true */
}
else{ /* statement(s) will execute if the    boolean expression is false */
}

如果布林表示式計算結果為 **true**,則執行 **if 程式碼塊**,否則執行 **else 程式碼塊**。

流程圖

下圖顯示了 if…else 語句的工作方式。

If  Else Statement

示例

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

import Foundation

var varA:Int = 100;

/* Check the boolean condition using if statement */
if varA < 20 {
   /* If the condition is true then print the following */
   print("varA is less than 20");

} else {
   /* If the condition is false then print the following */
   print("varA is not less than 20");
}

print("Value of variable varA is \(varA)");

輸出

它將產生以下輸出:

varA is not less than 20
Value of variable varA is 100

示例

Swift程式使用if-else語句檢查偶數或奇數。

import Foundation

let num = 41

if num % 2 == 0 {
   print("Entered number is even.")
} else {
   print("Entered number is odd.")
}

輸出

它將產生以下輸出:

Entered number is odd.

示例

Swift 程式使用 if-else 語句檢查正確的使用者名稱。

import Foundation

let username = "123Admin22"
let inputUsername = "123Admin22"

if username == inputUsername {
   print("Login successful.")
} else {
   print("Invalid username.")
}

輸出

它將產生以下輸出:

Login successful.
廣告