Swift - switch 語句



switch 語句是最強大的控制語句,它允許我們以易於閱讀的方式表示多分支邏輯。它提供了一種方法來根據多個給定的 case 評估值,並執行第一個匹配 case 中的語句塊。

switch 語句是 if-else 語句的替代方案,因為它比 if-else 語句更有效地處理多個條件。

語法

以下是 switch 語句的語法:

switch expression{
case 1: 
// Statement 
fallthrough // Optional
case 2: 
// Statement 
break // Optional
default: 
// Statement 

示例

以下是 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 switch 語句中的 break 語句

break 語句用於在執行匹配的 case 語句塊後立即終止 switch 塊,並將控制轉移到 switch 塊之後出現的語句。break 語句用於 case 塊中。

語法

以下是 break 語句的語法:

switch expression{
   case x:
   // Statement 
   break
   default:
   // Statement
}

示例

以下是 break 語句的示例:

import Foundation

let day = 4
switch day {
   // Case with the break statements
   case 1:
      print("Monday")
      break
   case 2:
      print("Tuesday")
      break
   case 3:
      print("Wednesday")
      break
   case 4:
      print("Thursday")
      break
   case 5:
      print("Friday")
      break
   default:
      print("Weekend")
}

輸出

它將產生以下輸出:

Thursday

Swift switch 語句中的 fallthrough

switch 語句一旦遇到第一個匹配的 case 就會結束執行,即使我們使用或不使用 break 語句也是如此。與 C 和 C++ 程式設計不同,控制不會貫穿後續 case 的底部。

如果我們想在 Swift 中實現 fallthrough 功能,則必須在每個 case 中顯式使用 fallthrough 語句。fallthrough 語句允許控制傳遞到下一個 case,即使該 case 的條件不匹配。

語法

以下是 fallthrough 語句的語法:

switch expression{
   case x:
   // Statement 
   fallthrough
   default:
   // Statement
}

示例

以下是 fallthrough 語句的示例:

import Foundation

let number = 2

switch number {

   // Case statement with fall through
   case 1:
      print("Hello i am case 1")
      fallthrough
   case 2:
      print("Hello i am case  2")
      fallthrough
   case 3:
      print("Hello i am case  3")
   default:
      print("Not found")
}

輸出

它將產生以下輸出:

Hello i am case  2
Hello i am case  3

Swift switch 語句中的範圍

在 Swift 中,我們允許在 case 語句中使用範圍來根據一系列元素匹配值。當我們想要處理值落在給定範圍內的 case 時,通常會使用它。

語法

以下是 case 語句中範圍的語法:

switch expression{
   case x…y:
   // Statement 
   default:
   // Statement
}

示例

以下是 case 語句中範圍的示例:

import Foundation

let temp = 27

switch temp {

// Case statement with ranges
case ..<0:
   print("Freezing.")
case 0...20:
   print("Cold.")
case 21...30:
   print("Moderate.")
case 31...:
   print("Hot")
default:
   print("Please enter valid temperature")
}

輸出

它將產生以下輸出:

Moderate.

Swift switch 語句中的元組匹配

眾所周知,元組用於將多個值儲存在一起,無論它們是否為同一型別。因此,我們允許在 switch 語句中使用元組作為變量表達式,也可以使用元組在 case 語句中測試多個值。我們也可以在元組中使用萬用字元模式“_”。

語法

以下是元組匹配的語法:

switch (x1, x2){
   case (y, x1):
   // Statement 
   default:
   // Statement
}

示例

以下是元組匹配的示例:

import Foundation	
// Switch expression in tuple
let number = (num1: 25, num2: 10, num3: 11)

switch number {
   // Case expression in tuple
   case (25, 10, 0):
      print("Numbers are (25, 10, 0)")
   case (13, _, 11):
      print("Numbers are (13, 11)")
   case (25, 10, 11):
      print("Number are (25, 10, 11)")
   default:
      print("Number is not found")
}

輸出

它將產生以下輸出:

Number are (25, 10, 11)

Swift switch 語句中的值繫結

Swift 提供了一個名為值繫結的新屬性。使用此屬性,我們允許在 case 語句中初始化一個臨時變數,並且此變數僅在其定義的 case 的主體中可用。或者我們可以說它將匹配值繫結到相關塊中的臨時變數或常量。

語法

以下是值繫結的語法:

switch expression{
   case (let x, let y):
   // Statement 
   default:
   // Statement
}

示例

以下是值繫結的示例:

import Foundation

let num = 17
switch num {
   // Value binding
   case let y where y % 2 == 0:
      print("\(num) is an even number.")
   case let z where z % 2 != 0:
      print("\(num) is an odd number.")
   default:
      print("\(num) is invalid number.")
}

輸出

它將產生以下輸出:

17 is an odd number.

Swift 帶 where 子句的 switch 語句

我們還可以將 where 子句與 case 條件一起使用以檢查額外條件。當我們想根據附加條件篩選 case 時,可以使用它。

語法

以下是帶有 where 子句的 case 的語法:

switch expression{
   case "0"…"8" where expression.isNumber: 
   // Statement 
   default:
   // Statement
}

示例

以下是帶有 where 子句的 case 的示例:

import Foundation
let marks = 77
switch marks {
case 0...59:
    print("Sorry! You are Failed")
    
   // Case with where clause
   case 60...79 where marks < 75:
      print("Congratulations! You are Passed")
   case 60...79 where marks >= 75:
      print("Congratulations! You are Passed with distinction")
   case 80...100:
      print("Excellent! You topped the Class")
   default:
      print("Not a valid score")
}

輸出

它將產生以下輸出:

Congratulations! You are Passed with distinction

Swift 中的複合 case

在 switch 語句中,我們允許在一個 case 中使用多個模式,其中 case 中的所有模式都用逗號分隔,並共享相同的程式碼塊。

如果任何給定的模式匹配,則將執行該 case 中的程式碼塊。當我們想要為各種 case 執行相同的程式碼塊時,通常會使用複合 case。

語法

以下是複合 case 的語法:

switch expression{
   case a, b, c: 
   // Statement 
   case x, y, z, w:
   // Statement
   default:
   // Statement
}

示例

以下是複合 case 的示例:

import Foundation

let number = 20

switch number {
   // Compound case
   case 10, 20, 30:
      print("Selected number is 10, 20 or 30")
   case 40, 50, 60:
      print("Selected number is 40, 50, 60")
   default:
      print("Value not found")
}

輸出

它將產生以下輸出:

Selected number is 10, 20 or 30
廣告