Swift - 決策制定



什麼是決策結構?

決策結構要求程式設計師指定一個或多個條件供程式評估或測試,以及在確定條件為true時要執行的語句,以及可選地在確定條件為false時要執行的其他語句。使用決策結構,程式設計師能夠建立靈活且響應迅速的程式,允許程式根據條件採取不同的路徑。

Decision Making Structure

Swift 中的決策語句型別

Swift 提供以下型別的決策語句。

語句 描述
if 語句 if 語句允許您在給定表示式為 true 時執行程式碼塊。
if…else 語句 if-else 語句允許您在 if 條件為 true 時執行程式碼塊。否則將執行 else 程式碼塊。
if…else if…else 語句 if…else if…else 語句用於按順序檢查多個條件,並執行與第一個 true 條件關聯的語句塊。
巢狀 if 語句 巢狀 if 語句用於在另一個語句內指定語句。
switch 語句 switch 語句允許將變數與其值列表進行相等性測試。

示例

Swift 程式演示 switch 語句的使用。

import Foundation

var index = 10

switch index {
   case 100 :
      print( "Value of index is 100")
   case 10,15 :
      print( "Value of index is either 10 or 15")
   case 5 :
      print( "Value of index is 5")
   default :
      print( "default case")
}

輸出

它將產生以下輸出:

Value of index is either 10 or 15

示例

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

import Foundation

let X = 40
let Y = 80

// Comparing two numbers
if X > Y {
   print("X is greater than Y.")
} else {
   print("Y is greater than or equal to X.")
}

輸出

它將產生以下輸出:

Y is greater than or equal to X.

Swift 三元條件運算子

三元條件運算子是 if-else 語句的簡寫表示形式。它包含三個部分:條件、結果1 和結果2。如果條件為 true,則它將執行結果1 並返回其值。否則,它將執行結果2 並返回其值。

語法

以下是三元條件運算子的語法:

Exp1 ? Exp2 : Exp3

其中 Exp1、Exp2 和 Exp3 是表示式。? 表示式的值如下確定:評估 Exp1。如果為真,則評估 Exp2 併成為整個 ? 表示式的值。如果 Exp1 為假,則評估 Exp3,其值成為表示式的值。

示例

Swift 程式使用三元條件運算子檢查數字是奇數還是偶數。

import Foundation
let num = 34

// Checking whether the given number is odd or even
// Using ternary conditional operator
let result = num % 2 == 0 ? "Even" : "Odd"
print("The number is \(result).")

輸出

它將產生以下輸出:

The number is Even.

示例

Swift 程式使用三元條件運算子檢查數字是正數還是負數。

import Foundation

let num = 34

// Checking whether the given number is positive or negative
// Using ternary conditional operator
let result = num >= 0 ? "Positive" : "Negative"
print("Given number is \(result).")

輸出

它將產生以下輸出:

Given number is Positive.
廣告