Swift - 結構體



結構體是Swift中最常用的使用者自定義資料型別。它允許我們將相關資料和操作組合到單個塊中。它對於將資料和功能封裝到單個單元中非常有用,並提供更組織化和可讀的程式碼。在結構體中,我們可以藉助方法和屬性新增功能。

在Swift中,結構體不需要任何額外的檔案或介面來實現,我們可以在單個檔案中定義結構體,外部介面會自動訪問此程式碼。結構體是值型別。

Swift中的結構體

就像其他程式語言一樣,在Swift中,結構體使用struct關鍵字以及名稱和花括號({})定義。這裡名稱必須以大寫字母開頭,例如School,而不是school。花括號包含所有屬性和方法。

  • 屬性 - 與結構體關聯的常量和變數稱為結構體的屬性。它們通常用於儲存和檢索結構體例項中的值。一個結構體可以有多個屬性。

  • 方法 - 與結構體關聯的函式稱為結構體的方法。它們通常用於定義與結構體相關的行為。方法可以具有引數和返回值。一個結構體可以有多個方法。在Swift中,使用方法不允許我們更改屬性。但是,如果我們想在方法內部更改屬性,則必須使用mutating關鍵字標記該方法。

語法

以下是結構體的語法:

struct nameStruct { 
   // Properties
   Property 1 : Type
   Property 2 : Type

   // Methods
   func functionName(){
      // Statement
   } 
   
   // Mutating method
   mutating func functionName(){
      // Statement
   }
}

示例

在下面的Swift示例中,我們需要訪問包含三門科目分數的學生記錄,並計算這三門科目的總分。因此,我們建立一個名為markStruct的結構體,其中包含三個名為'Int'的資料型別的分數。

struct MarkStruct{
   var mark1: Int
   var mark2: Int
   var mark3: Int
}

Swift結構體例項

結構體例項是從結構體的定義建立的物件,並代表屬性的一些值集。單個結構體可以有多個例項,它們彼此獨立,這意味著如果我們修改一個例項,不會影響其他例項。

我們可以透過呼叫結構體初始化器來建立一個結構體例項。結構體可能包含也可能不包含初始化器。因此,如果結構體不包含任何初始化器,則Swift將自動接收一個逐成員初始化器來建立結構體物件。使用此初始化器,我們可以透過在逐成員初始化器中傳遞初始值以及名稱來初始化每個屬性。

語法

以下是結構體例項的語法:

var objectName = StructName(propertyName1: value, propertyName2: value)

示例

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

struct MarkStruct{
   var mark1: Int
   var mark2: Int
   var mark3: Int
}

// Creating instance using memberwise initializer
var myObj = MarkStruct(mark1: 10, mark2: 20, mark3: 30)

如果結構體包含預設初始化器,我們也可以在不提供引數或初始值的情況下建立結構體的例項。

struct MarkStruct{
   var mark1: Int
   var mark2: Int
   var mark3: Int

   // Default initialzer
   init(){
      Mark1  = 1
      Marks2 = 2
      Mark3 = 3
   }
}

// Creating instance using default initializer
var myInstance = MarkStruct()

在Swift中訪問結構體的屬性

要訪問結構體的屬性,我們可以使用結構體例項後跟一個點(.)和屬性名稱。使用此表示法,我們還可以修改屬性的值。藉助此表示法,我們還可以訪問和修改結構體的子屬性。

語法

以下是訪問結構體屬性的語法:

structInstanceName.PropertyName

以下是修改結構體屬性的語法:

structInstanceName.PropertyName = value

以下是訪問結構體子屬性的語法:

structInstanceName.PropertyName.subPropertyName

以下是修改結構體子屬性的語法:

structInstanceName.PropertyName.subPropertyName = value

示例

Swift程式,用於訪問和修改結構體的屬性。

// Defining a structure
struct Employee {
   var name: String
   var age: Int
   var department: String
   var salary: Int
}

// Creating an instance of the Employee structure 
// with initial values of the properties
var emp = Employee(name: "Mona", age: 22, department: "HR", salary: 32000)

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

// Modifying the values of the properties using dot notation
emp.age = 23
emp.salary = 33000

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

輸出

它將產生以下輸出:

Employee Details:
Name: Mona
Age: 22
Department: HR
Salary: 32000

Updated Values:
Age: 23
Salary: 33000

示例

Swift程式,用於訪問和修改結構體的子屬性。

// Defining a structure with sub-properties
struct Address {
   var buildingName: String
   var city: String
   var pincode: String
}

// Defining a structure 
struct Student {
   var name: String
   var age: Int
   var address: Address
}

// Creating an instance of the Student structure 
// with initial values of the properties
var stud = Student(name: "Sumit", age: 22, address: Address(buildingName: "Anad Vihar", city: "Delhi", pincode: "333333"))

// Accessing the values of the properties and sub-properties using dot notation
print("Student Details:")
print("Name: \(stud.name)")
print("Age: \(stud.age)")
print("Building Name: \(stud.address.buildingName)")
print("City: \(stud.address.city)")
print("Pincode: \(stud.address.pincode)")

// Modifying the values of the sub-properties using dot notation
stud.address.buildingName = "Mohita Vihar"
stud.address.pincode = "333000"

// Displaying the updated values
print("\nUpdated Values:")
print("Building Name: \(stud.address.buildingName)")
print("Pincode: \(stud.address.pincode)")

輸出

它將產生以下輸出:

Student Details:
Name: Sumit
Age: 22
Building Name: Anad Vihar
City: Delhi
Pincode: 333333

Updated Values:
Building Name: Mohita Vihar
Pincode: 333000

在Swift中訪問結構體的方法

藉助點表示法,我們還可以訪問結構體的方法。在這裡,我們也可以使用結構體例項後跟一個點(.)和方法名稱來訪問方法。

語法

以下是訪問結構體方法的語法:

structInstanceName.methodName

示例

Swift程式,用於訪問結構體的方法。

// Defining a structure 
struct Parallelogram {
   var base: Double
   var height: Double

   // Method to calculate the area of the Parallelogram
   func calculateParallelogramArea() -> Double {
      return base * height
   }

   // Mutating method to resize the base and height of the Parallelogram 
   mutating func resizeParallelogram(by value: Double) {
      base += value
      height += value
   }
}

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

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

// Calling the mutating method i.e., resizeParallelogram()
myObj.resizeParallelogram(by: 3)

// Displaying the updated base and height of the Parallelogram
print("\nUpdated values: ")
print("Base: \(myObj.base)")
print("Height: \(myObj.height)")

輸出

它將產生以下輸出:

Area of the Parallelogram: 90.0

Updated values: 
Base: 13.0
Height: 12.0

Swift中結構體作為值型別

在Swift中,結構體是值型別,這意味著當我們將結構體賦值給變數或常量或將其作為引數傳遞給函式時,會建立一個結構體的副本。這些副本與原始例項獨立,這意味著如果我們修改一個例項的副本,不會影響結構體例項的其他副本。

示例

Swift程式,用於演示結構體作為值型別。

// Defining a structure 
struct Student {
   var name: String
   var age: Int
}

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

// Creating a copy of the stud instance
var details = stud

// Modifying the values of the properties
details.name = "Mohina"
details.age = 34

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

輸出

它將產生以下輸出:

student 1: name-Sumit and age-22
student 2: name-Mohina and age-34

Swift中帶有self關鍵字的結構體

在結構體中,self關鍵字用於區分屬性名稱和方法的引數。self關鍵字通常與方法或初始化器內部的屬性一起使用,以便編譯器可以輕鬆區分哪個是引數,哪個是屬性(如果它們的名稱相同)。或者self關鍵字用於引用結構體的當前例項。

語法

以下是self關鍵字的語法:

self.PropertyName

示例

Swift程式,用於演示如何在結構體中使用self關鍵字。

// Defining a structure 
struct markStruct{ 
   var mark1: Int
   var mark2: Int
   var mark3: Int
   
   // Initializer with same property and parameter name
   init(mark1: Int, mark2: Int, mark3: Int){
   
      // Using self keyword to distinguish between 
      // the property and parameter name
      // Here self.mark1 is the property name 
      self.mark1 = mark1
      self.mark2 = mark2
      self.mark3 = mark3
   }
}

// Creating an instance of the structure
var marks = markStruct(mark1: 98, mark2: 96, mark3:100)

// Displaying the values of the properties
print(marks.mark1)
print(marks.mark2)
print(marks.mark3)

輸出

它將產生以下輸出:

98
96
100

在Swift中將結構體傳遞給函式

在Swift中,允許我們將結構體作為引數傳遞給函式,方法是將結構體指定為引數的型別。結構體始終按值傳遞,這意味著結構體的副本將作為引數傳遞,修改不會影響原始結構體。在函式中,如果我們不想修改結構體,則可以將其作為常規引數傳遞;如果我們想修改結構體,則必須將其作為inout引數傳遞。

示例

Swift程式,用於演示如何將結構體傳遞給函式。

// Defining a structure 
struct Rectangle {
   var length: Double
   var width: Double
}

// Passing a structure to a function as a regular parameter
func areaOfRectangle(value:Rectangle){
   print("Area of the Rectangle is \(value.length * value.width)")
}

// Passing a structure to a function as an inout parameter
// Because we will modify the structure
func newAreaOfRectangle(data:inout Rectangle, byL newLength : Double, byW newWidth : Double){
   data.length *= newLength
   data.width *= newWidth
   print("New Area of the Rectangle is \(data.length * data.width)")
}

// Create an instance of the rectangle structure
var myObj = Rectangle(length: 10.0, width: 9.0)

// Calling the function
areaOfRectangle(value:myObj)

// Calling the another function 
newAreaOfRectangle(data: &myObj, byL : 2, byW : 3)

輸出

它將產生以下輸出:

Area of the Rectangle is 90.0
New Area of the Rectangle is 540.0
廣告