Swift - 列舉



列舉是一種使用者定義的資料型別,它由一組相關的值組成,並提供了一種以型別安全的方式處理這些值的方法。列舉通常不為每個情況提供值,但如果需要,可以為每個列舉情況分配值,並且該值可以是任何型別,例如字串、整數、浮點數或字元。

Swift 中的列舉

我們可以使用enum關鍵字後跟名稱和花括號來定義列舉,其中花括號包含使用case關鍵字的列舉情況。列舉名稱應以大寫字母開頭(例如:enum DaysofaWeek)。

語法

以下是列舉的語法:

enum EnumName {
   // enumeration cases
   case value1
   case value2
   ...
   case valueN
}

我們還可以將多個列舉情況定義在一行中,其中每個情況用逗號分隔。

enum EnumName {
   // enumeration cases
   case value1, value2, value3,…,valueN
}

示例

以下是 Swift 的示例,演示如何建立列舉:

enum CarColor {
   // enum values
   case Blue
   case Green
   case White
   case Off-white
}

在 Swift 中建立列舉變數

在列舉中,我們可以直接建立一個列舉型別變數併為其分配一個情況。我們可以使用點(.)表示法將情況分配給列舉變數,其中點表示法後跟值(例如:.value)。

語法

以下是建立列舉變數的語法:

var variableName : EnumName 

以下是為列舉變數賦值的語法:

variableName = .enumValue

示例

Swift 程式用於建立和訪問列舉變數。

// Defining an enumeration with cases representing subjects
enum Subjects {
   case Maths
   case Science
   case Social
   case English
   case Hindi
   case ComputerProgramming
}

// Creating and assigning value to an enum variable 
var name: Subjects = .English

// Access the value of the enum variable and display data accordingly
switch name {
   case .English, .Hindi, .ComputerProgramming:
      print("Elective subjects!")
   case .Maths, .Science, .Social:
      print("Compulsory subjects")
}

輸出

它將產生以下輸出:

Elective subjects!

示例

Swift 程式用於建立和訪問列舉變數。

// Defining an enumeration with cases representing car colour
enum Subjects {
   case Black
   case Blue
   case MidnightGray
   case White
   case OffWhite
   case Silver
}

// Creating and assigning value to an enum variable 
var color: Subjects = .Blue

// Using an if statement to check the enum value
if color == .Blue {
   print("Dark edition of car")
}

輸出

它將產生以下輸出:

Dark edition of car

Swift 中帶有原始值的列舉

在列舉中,我們還可以為列舉情況分配值,這些值稱為原始值。原始值可以是字串、字元或任何整數或浮點數型別。每個原始值在其列舉宣告中必須是唯一的,並且型別相同。

語法

以下是為列舉情況分配原始值的語法:

enum enumName : Type{
   // enum values
   case value1 = RawValue1
   case value2 = RawValue2
}

訪問原始值

我們可以藉助名為rawValue的預定義屬性來訪問原始值。rawValue屬性用於檢索與指定列舉情況關聯的原始值。

語法

以下是rawValue屬性的語法:

let variableName = enumName.enumCase.rawValue

示例

Swift 程式用於使用rawValue屬性訪問列舉的原始值。

// Defining an enumeration with cases representing car colour
enum CarColor : Int {
   case Black = 2
   case Blue = 4
   case OffWhite = 5
   case Silver = 6
}

// Accessing the raw value
var colorCount = CarColor.Blue.rawValue

// Displaying the raw values
print("Raw Value:", colorCount)
輸出

它將產生以下輸出:

Raw Value: 4

隱式分配原始值

當整數或字串用作列舉情況的原始值時,則無需為每個列舉情況指定值,因為 Swift 將自動為每個列舉情況分配值。此類方法稱為隱式分配原始值。

當我們使用 Integer 型別作為列舉情況的原始值併為第一個情況提供原始值時,Swift 將自動為後續情況分配原始值,其中分配給當前情況的值大於前一個情況的值。

示例

Swift 程式用於隱式分配 Integer 型別的原始值。

// Defining an enumeration with cases representing marks subject 
enum SubjectMarks: Int {

   // Assigning raw value to the first case
   // Now Swift will automatically assign raw values to the cases
   // for english = 41, hindi = 42, and physics = 43
   case maths = 40, english, hindi, physics
}

// Accessing the raw value
let marks = SubjectMarks.hindi.rawValue

print("Marks of hindi = ", marks)
輸出

它將產生以下輸出:

Marks of hindi =  42

如果我們不為第一個情況分配原始值,則預設情況下,Swift 將為第一個情況分配零,然後為第二個情況分配 1,為第三個情況分配 2,依此類推。

示例

// Defining an enumeration with cases representing marks subject 
enum SubjectMarks: Int {
   // Here we do not assign raw value to the first case
   // So Swift will automatically assign default raw values
   case maths         // Default raw value = 0
   case english       // Default raw value = 1
   case hindi         // Default raw value = 2
   case physics       // Default raw value = 3
}

// Accessing the raw value
let marks = SubjectMarks.hindi.rawValue

print("Marks of hindi = ", marks)
輸出

它將產生以下輸出:

Marks of hindi =  2

當我們使用 String 型別作為列舉情況的原始值並且不為情況提供原始值時。然後,預設情況下,Swift 將隱式分配情況的名稱作為原始值。

示例

Swift 程式用於隱式分配 String 型別的原始值。

// Defining an enumeration with cases representing subject names 
enum Subjects: String{
   // Here we do not assign raw value to the cases
   // So Swift will automatically assign default raw values
   case maths         // Default raw value = maths
   case english       // Default raw value = english
   case hindi         // Default raw value = hindi
   case physics       // Default raw value = physics
}

// Accessing the raw value
let marks = Subjects.hindi.rawValue

print("Marks of hindi = ", marks)
輸出

它將產生以下輸出:

Marks of hindi =  hindi

從原始值初始化

在定義帶有原始值型別的列舉時,Swift 會自動為該列舉建立一個初始化器,該初始化器將原始值作為引數並返回一個可選值(一個情況或 nil)。如果原始值與任何給定情況匹配,則初始化器將返回包含在可選值中的該情況,而如果原始值與任何給定情況都不匹配,則它將返回 nil。

示例

Swift 程式用於從原始值初始化。

// Defining an enumeration with raw values of string type
enum Fruits: String {
   case value1 = "Mango"
   case value2 = "Apple"
   case value3 = "Banana"
   case value4 = "Orange"
}

// Initializing from raw values
if let result = Fruits(rawValue: "Apple") {
   print("Case '\(result)' is found for the given raw value")
} else {
   print("No is case found")
}
輸出

它將產生以下輸出:

Case 'value2' is found for the given raw value

Swift 中帶有關聯值的列舉

帶有關聯值的列舉是 Swift 提供的最重要的功能。它允許我們在列舉的每個情況中新增一些其他資訊。它通常用於型別可以具有不同變體和不同關聯資料的情況。

示例

Swift 程式演示帶有關聯值的列舉。

// Defining an enumeration with associate values
enum Student{
   case Name(String)
   case Mark(Int, Int, Int)
}

// Creating instances of the enum
var studDetails = Student.Name("Swift")
var studMarks = Student.Mark(98, 97, 95)

// Accessing the associate values
switch studMarks {
   case .Name(let studName):
      print("Student name is: \(studName).")
   case .Mark(let Mark1, let Mark2, let Mark3):
      print("Student Marks are: \(Mark1), \(Mark2), \(Mark3).")
}

輸出

它將產生以下輸出:

Student Marks are: 98, 97, 95.

關聯值和原始值之間的區別

關聯值 原始值
不同資料型別 相同資料型別
例如:enum {10,0.8,"Hello"} 例如:enum {10,35,50}
基於常量或變數建立的值 預填充值
每次宣告時都不同 成員的值相同

Swift 中使用 Switch 語句的列舉

正如我們所知,Switch 語句也遵循多路選擇,這意味著根據指定的條件,一次只能訪問一個變數。因此,我們可以使用 Switch 語句來處理列舉的不同情況。

示例

Swift 程式演示使用 Switch 語句的列舉。

// Defining an enumeration with cases
enum Climate {
   case India
   case America
   case Africa
   case Australia
}

// Accessing enumeration cases using a switch statement
var season = Climate.America
season = .America
switch season {
   case .India:
      print("Climate is Hot")
   case .America:
      print("Climate is Cold")
   case .Africa:
      print("Climate is Moderate")
   case .Australia:
      print("Climate is Rainy")
}

輸出

它將產生以下輸出:

Climate is Cold

在 Swift 中迭代列舉

要迭代列舉,我們必須使用“CaseIterable”協議。此協議提供給定列舉的所有情況的集合。然後,我們將在迴圈中使用allCases屬性來迭代每個情況,其中迭代的順序取決於定義情況的順序。如果需要按特定順序排列情況,則相應地定義它們。

示例

Swift 程式用於迭代給定的列舉。

// Defining enumeration with cases
enum Veggies: CaseIterable {
   case Onion
   case Carrot
   case Beetroot
   case Tomato
   case GreenChilly
}

// Iterating over the given enumeration
for x in Veggies.allCases {
   print(x)
}

輸出

它將產生以下輸出:

Onion
Carrot
Beetroot
Tomato
GreenChilly

Swift 中的遞迴列舉

在 Swift 中,我們允許建立遞迴列舉。遞迴列舉是一種特殊的列舉,其中情況可以具有列舉型別本身的關聯值。我們必須在遞迴列舉情況之前使用indirect關鍵字,它告訴編譯器新增所有必要的間接層。此外,並非給定列舉中存在的所有情況都需要標記為間接,只有那些涉及遞迴的情況才應標記為間接。

示例

Swift 程式演示遞迴列舉。

// Recursive enumeration for representing arithmetic expressions
enum Calculator {
   case number(Int)
    
   // Cases that involve recursion
   indirect case sum(Calculator, Calculator)
   indirect case product(Calculator, Calculator)
}

// Expressions
let num1 = Calculator.number(10)
let num2 = Calculator.number(12)

let addition = Calculator.sum(num1, num2)
let prod = Calculator.product(num1, addition)

// Function to evaluate an expression
func result(_ exp: Calculator) -> Int {
   switch exp {
      case let .number(value):
         return value
      case let .sum(left, right):
         return result(left) + result(right)
      case let .product(left, right):
         return result(left) * result(right)
   }
}

// Displaying result
let output = result(addition)
print("Sum is  \(output)")

輸出

它將產生以下輸出:

Sum is  22
廣告