Swift 程式實現字串的 switch 語句
switch 語句是一種控制流語句,它只在 switch 語句中給定的表示式與多個給定 case 中的一個匹配時才執行程式碼塊。如果沒有任何 case 滿足給定的表示式,則 switch 語句執行 default case。在 Swift 中,我們允許對字串實現 switch 語句。
語法
switch (expression)
{
case 1:
// Block of code
case 2:
// Block of code
.
.
.
default:
// Block of code
}
在這裡,switch 語句評估表示式,並且只執行匹配的 case。其中表達式可以是任何型別,但在我們的例子中是字串型別。
演算法
步驟 1 - 建立一個變數來儲存字串型別的表示式。
步驟 2 - 將變數分配給 switch 語句。
步驟 3 - 現在 switch 語句檢查是否有任何給定的 case 與指定的表示式匹配。
步驟 4 - 如果匹配,則執行指定 case 中給出的程式碼塊。否則,執行 default 語句。
步驟 5 - 列印輸出。
示例 1
在下面的 Swift 程式中,我們將對字串實現 switch 語句。所以首先我們將字串型別的表示式賦值給一個變數,然後檢查每個 case。如果找到匹配項,則執行相應的程式碼塊。如果找不到匹配項,則它將執行 default case。在本例中,box = “Pencil”,因此將執行“Pencil” case 中的程式碼。
import Foundation
import Glibc
let box = "Pencil"
switch box {
case "Eraser":
print("Geometry Box contain Eraser")
case "Pen":
print("Geometry Box contain Pen")
case "Pencil":
print("Geometry Box contain Pencil")
case "Ruler":
print("Geometry Box contain Ruler")
default:
print("Geometry Box does not contain the specified item")
}
輸出
Geometry Box contain Pencil
示例 2
在下面的 Swift 程式中,我們將對字串實現 switch 語句。所以首先我們將字串型別的表示式賦值給一個變數,然後將該變數賦值給 switch 語句,然後使用逗號分隔格式 (case “Eraser”, “Pencil”:) 為多個字面量建立多個 case。因此,如果 box 的值為“Pencil”或“Eraser”,則相應 case 語句中的程式碼將執行。其他 case 類似。如果找不到匹配項,則它將執行 default case。在本例中,box = “Pencil”,因此將執行“Eraser”, “Pencil” case 語句中的程式碼。
import Foundation
import Glibc
let box = "Pencil"
switch box {
case "Eraser", "Pencil":
print("Geometry Box contain Eraser and Pencil")
case "Pen", "Ink":
print("Geometry Box contain Pen and Ink")
case "Ruler", "Compass":
print("Geometry Box contain Ruler and Compass")
default:
print("Geometry Box does not contain the specified item")
}
輸出
Geometry Box contain Eraser and Pencil
示例 3
在下面的 Swift 程式中,我們將對字串實現 switch 語句。所以首先我們將字串型別的表示式賦值給一個變數,然後將該變數賦值給 switch 語句,然後建立多個 case,在每個 case 中我們指定一個特定的範圍,例如“G”...”M”,它表示以字母 G 到 M 開頭的名稱。如果在某個 case 中找到了名稱字母,則執行其中的程式碼。如果找不到匹配項,則執行 default case。
import Foundation
import Glibc
let name = "Pushpa"
switch name {
case "A"..."F":
print("Employees whose name starts with A to F are transferred to Group MAX")
case "G"..."M":
print("Employees whose name starts with G to M are transferred to Group MIN")
case "N"..."S":
print("Employees whose name starts with N to S are transferred to Group MIDDLE")
case "T"..."Z":
print("Employees whose name starts with T to Z are transferred to Group SUPER")
default:
print("Invalid name! Try again")
}
輸出
Employees whose name starts with N to S are transferred to Group MIDDLE
結論
這就是我們如何在字串上實現 switch 語句的方法。在 switch 語句中,我們可以根據需要新增更多 case。switch 語句就像 if-else-if 語句,但與 if-else-if 語句相比,它更清晰易讀。
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP