Swift - 類



Swift 中的類是靈活結構的構建塊。類似於常量、變數和函式,使用者可以定義類屬性和方法。Swift 為我們提供了這樣的功能:在宣告類時,使用者無需建立介面或實現檔案。Swift 允許我們將類建立為單個檔案,並且一旦類初始化,外部介面將預設建立。

擁有類的優勢

  • 繼承將一個類的屬性獲取到另一個類。

  • 型別轉換使使用者能夠在執行時檢查類型別。

  • 解構函式負責釋放記憶體資源。

  • 引用計數允許類例項擁有多個引用。

類和結構體的共同特徵

  • 屬性用於儲存值

  • 下標定義為提供對值的訪問

  • 方法初始化以改進功能

  • 初始狀態由初始化器定義

  • 功能擴充套件到預設值之外

  • 確認協議功能標準

Swift 中類的定義

在 Swift 中,使用 class 關鍵字以及類名和花括號({}) 來定義。類名始終以大寫字母開頭,例如 Employee,而不是 employee,花括號包含類的初始化器、屬性和方法。

  • 屬性 - 與類關聯的常量和變數稱為結構體的屬性。它們通常用於定義類的特徵。一個類可以有多個屬性。

  • 方法 - 與類關聯的函式稱為類的方法。它們通常用於定義與類關聯的行為。它們可以具有引數和返回值。單個類可以有多個方法。

  • 初始化器 - 它是與類關聯的一種特殊方法。初始化器用於設定類例項的初始狀態。它使用 init 關鍵字定義。在建立類例項時呼叫它。它可以具有引數和預設值。

語法

以下是類的語法:

class nameClass { 
   // Properties
   Property 1 : Type
   Property 2 : Type

   // Initializer
   init(){
      // statement
   }

   // Methods
   func functionName(){
      // Statement
   } 
}

示例

在下面的 Swift 示例中,我們建立了一個名為 markStruct 的類,它具有三個屬性,例如 String 型別的 studname,以及 Int 型別的 mark 和 mark2。

class student{
   var studname: String
   var mark: Int 
   var mark2: Int 
}

Swift 類物件

物件稱為類的例項。它是根據類定義的藍圖建立的。單個類可以有多個物件,並且它們彼此獨立,這意味著如果我們修改一個例項,則不會影響其他例項。我們可以透過呼叫類初始化器來建立類的物件。使用此初始化器,我們可以透過將初始值與屬性名稱一起傳遞來初始化每個屬性。

語法

以下是類例項的語法:

var objectName = ClassName(propertyName1: Value, propertyName2: value)

示例

在下面的 Swift 示例中,我們將建立 Marks 的例項。

class Marks {
   var mark1: Int
   var mark2: Int
   var mark3: Int
}
// Creating a class object using an initializer
var myObj = Marks(mark1: 10, mark2: 20, mark3: 30)

在 Swift 中訪問類的屬性

要訪問類的屬性,我們可以使用類物件後跟一個點(.)和屬性的名稱。我們還可以藉助點(.)語法修改屬性的值。

語法

以下是訪問類屬性的語法:

classObjectName.PropertyName

以下是修改類屬性的語法:

classObjectName.PropertyName = value

示例

Swift 程式用於訪問和修改類的屬性。

// Defining a class 
struct Employee {
   var name: String
   var department: String
   var salary: Int
    
   // Initializer
   init(name: String, department: String, salary: Int){
      self.name = name
      self.department = department
      self.salary = salary
   }
}

// Creating an instance of the Employee class
var emp = Employee(name: "Suman", department: "Designing", salary: 33000)

// Accessing the values of the properties using dot notation
print("Employee Details:")
print("Name: \(emp.name)")
print("Department: \(emp.department)")
print("Salary: \(emp.salary)")

// Modifying the values of the properties using dot notation
emp.salary = 40000

// Displaying the updated values
print("\nUpdated Value:")
print("Salary: \(emp.salary)")

輸出

它將產生以下輸出:

Employee Details:
Name: Suman
Department: Designing
Salary: 33000

Updated Value:
Salary: 40000

在 Swift 中訪問類的方法

要訪問類的方法,我們可以使用點表示法。這裡,類例項後跟一個點(.)和方法名稱來訪問方法。

語法

以下是訪問類方法的語法:

classInstanceName.methodName

示例

Swift 程式用於訪問類的方法。

// Defining a class 
class Parallelogram {

   // Properties of class
   var base: Double
   var height: Double
    
   // Initializer
   init(base: Double, height: Double){
      self.base = base
      self.height = height
   }
    
   // Method to calculate the area of the Parallelogram
   func calculateParallelogramArea() -> Double {
      return base * height
   }
}

// Create an instance of the Parallelogram class
var myObj = Parallelogram(base: 10.0, height: 9.0)

// Calling the calculateParallelogramArea() method
let area = myObj.calculateParallelogramArea()
print("Area of the Parallelogram: \(area)")

輸出

它將產生以下輸出:

Area of the Parallelogram: 90.0

類作為 Swift 中的引用型別

在 Swift 中,類是引用型別,這意味著當我們將類分配給結構體或常量或將其作為引數傳遞給函式時,將使用現有物件的引用。因此,當我們對一個例項進行更改時,將反映在該例項的所有引用中。

示例

Swift 程式演示類作為引用型別。

// Defining a class
class Student {

   // Properties
   var name: String
   var age: Int
    
   // Initializer    
   init(name: String, age: Int){
      self.name = name
      self.age = age
   }
}

// Creating an instance of the Student class 
var stud = Student(name: "Kunal", age: 22)

// Assigning stud to details
// Here details have the reference of stud object
var details = stud

// Modifying the values of the properties
// Here the modification will affect the stud instance 
// because it passed as a reference-type 
details.name = "Mohina"
details.age = 40

print("student 1: name-\(stud.name) and age-\(stud.age)")
print("student 2: name-\(details.name) and age-\(details.age)")

輸出

它將產生以下輸出:

student 1: name-Mohina and age-40
student 2: name-Mohina and age-40
廣告