Swift - 方法



方法是特定型別(如類、結構體或列舉)的函式。它們定義了型別例項的行為和功能。它們通常由例項訪問。Swift 還支援與型別本身關聯的型別方法。

Swift 中的例項方法

在 Swift 中,例項方法是屬於類、結構體或列舉特定例項的函式。它們在型別的例項上呼叫,並且可以訪問和修改例項屬性或其他例項方法,或者新增與例項需求相關的功能。

例項方法的語法與函式相同。例項方法也可以具有引數、返回型別、引數名稱和引數標籤。它可以寫在 {} 花括號內。它隱式地訪問型別例項的方法和屬性。例項方法只能使用該特定型別的例項來呼叫,不允許在沒有例項的情況下呼叫例項方法。

語法

以下是例項方法的語法:

func methodname(Parameters) -> returntype
{
   Statement1
   Statement2
   ---
   Statement N
   return parameters
}

例項方法使用“.”點語法訪問。

instanceName.methodName()

示例

// Defining a class
class Calculations {

   // Properties
   let a: Int
   let b: Int
   let res: Int
    
   // Initializer
   init(a: Int, b: Int) {
      self.a = a
      self.b = b
      res = a + b
   }
    
   // Instance method
   func tot(c: Int) -> Int {
      return res - c
   }
    
   // Instance method
   func result() {
      print("Result is: \(tot(c: 20))")
      print("Result is: \(tot(c: 50))")
   }
}

// Creating and initializing the instance of the class
let pri = Calculations(a: 600, b: 300)

// Accessing the instance method
pri.result()

輸出

它將產生以下輸出:

Result is: 880
Result is: 850

可變例項方法

在 Swift 中,結構體和列舉是值型別,這意味著我們不能在例項方法中更改屬性。因此,要在方法內部修改屬性,我們需要使用 mutating 關鍵字將該方法指定為可變方法,並且該方法在其屬性中所做的更改將在方法結束時寫回原始結構。

我們只能修改結構體和列舉的方法,而不能修改類的方法,因為類是引用型別,因此它們的屬性可以在不使用 mutating 關鍵字的情況下修改。此外,我們不能在結構體型別的常量上呼叫可變方法。

語法

以下是可變例項方法的語法:

mutating func methodname(Parameters) -> returntype
{
   Statement
}

示例

Swift 程式演示結構體中的可變方法。

// Defining a structure
struct CalculateSum {

   // Properties
   var num1 = 1
   var num2 = 1
    
   // Instance method
   func sum() -> Int {
      return num1 + num2
   }
    
   // Mutating instance method
   mutating func increment(res: Int) {
      num1 *= res
      num2 *= res
        
      print("New Number 1 is ", num1)
      print("New Number 2 is ", num2)
   }
}

// Creating and initializing the instance of structure
var obj = CalculateSum(num1: 10, num2: 12)

// Calling mutating method
obj.increment(res: 10)

// Calling instance method
print("Sum is ", obj.sum())

輸出

它將產生以下輸出:

New Number 1 is  100
New Number 2 is  120
Sum is  220

在可變方法中將例項分配給 self

在可變方法中,允許我們將新例項分配給隱式 self 屬性。它將用新例項替換現有例項。將新例項分配給 self 時,務必小心,因為它會更改例項的狀態,並且與原始例項相關的任何引用都不會反映這些更改。

示例

Swift 程式演示如何在可變方法中將例項分配給 self。

// Defining a structure
struct Student {
   var age: Int
   var name: String
    
   // Mutating method that assigns a new instance to self
   mutating func newValue() {
      self = Student(age: 23, name: "Jyoti")
   }
}

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

// Calling the mutating method
obj.newValue()

// Displaying the updated values
print("New age: \(obj.age), New name: \(obj.name)")
輸出

它將產生以下輸出:

New age: 23, New name: Jyoti

Swift 中的方法引數標籤和引數名稱

就像函式一樣,方法也可以為其引數和引數設定標籤和名稱。這些標籤和名稱為引數和引數提供了清晰且描述性的上下文。引數名稱用於方法的宣告中,而引數標籤用於呼叫方法時。預設情況下,引數標籤和引數名稱相同,但多個引數可以具有相同或唯一的引數標籤。引數的名稱應該唯一,以便編譯器可以輕鬆地區分它們。我們還可以透過在引數名稱前放置下劃線 (_) 來忽略引數標籤。

語法

以下是引數標籤和引數名稱的語法:

// Parameter name With argument label
func methodname(argumentLabel parameterName: Type, parameterName: Type) -> returntype
{
   Statement
   return value
}
methodname(name1:value, name2: value)

// Parameter name without argument label
func methodname(_name1: Type, _name2: Type) -> returntype
{
   Statement
   return value
}
methodname(value1, value2)

示例

Swift 程式演示如何在方法中指定引數名稱和引數標籤。

// Defining class
class CalculateSum {
    
   // Method with parameter name and argument label
   func addingTwoNumbers(num1 x: Int, num2 y: Int) -> Int {
      return x + y
   }
    
   // Method without argument label
   func addingThreeNumbers(_ x: Int, _ y: Int, num1 z: Int) -> Int {
      return x + y + z
   }
}

// Creating an instance of CalculateSum class
let obj = CalculateSum()

// Calling the method with parameter name and argument label
let result1 = obj.addingTwoNumbers(num1: 10, num2: 20)

// Calling the method without argument label
let result2 = obj.addingThreeNumbers(20, 30, num1: 40)

print("Sum of two numbers:", result1)
print("Sum of three numbers:", result2)

輸出

它將產生以下輸出:

Sum of two numbers: 30
Sum of three numbers: 90

方法中的 self 屬性

self 關鍵字用於區分屬性名稱和方法的引數。self 關鍵字通常與例項方法、可變方法或初始化程式中的屬性一起使用,以便編譯器可以輕鬆地區分哪個是引數,哪個是屬性(如果它們的名稱相同)。或者 self 關鍵字用於引用當前例項以獲取其定義的方法。我們可以在結構體、類和列舉中使用 self 關鍵字。

語法

以下是 self 關鍵字的語法:

self.PropertyName

示例

Swift 程式演示如何使用 self 關鍵字。

// Defining class
class Student {
   var name: String
    
   // Initializer 
   init(name: String) {
      self.name = name
   }
    
   // Instance method using self
   func greet(name: String) {
      self.name = name
      print("Hello, my name is \(self.name).")
   }
}

// Creating an instance of the Student class
var obj = Student(name: "Mona")

// Calling the greet method
obj.greet(name: "Mohina")

輸出

它將產生以下輸出:

Hello, my name is Mohina.

型別方法

Swift 支援一種稱為型別方法的特殊型別的函式。型別方法在型別本身上呼叫,而不是在型別的例項上呼叫。這些方法在結構體和列舉中由static關鍵字表示,而在類中由class關鍵字表示。在類中,型別方法允許子類覆蓋超類的型別方法實現。型別方法使用點 (.) 表示法訪問。

在型別方法中,屬性將引用型別本身,而不是型別的例項,這意味著我們可以區分型別屬性和型別方法引數。型別方法允許在其他方法名稱內呼叫另一個型別方法,而無需使用任何字首型別名稱。類似地,在結構體和列舉中,型別方法可以透過使用屬性名稱而不使用任何字首型別來訪問型別屬性。

語法

以下是結構體和列舉中型別方法的語法:

static func methodname(Parameters) -> returntype
{
   Statement
}

以下是類中型別方法的語法:

class ClassName{
   class func methodname(Parameters) -> returntype
   {
      Statement
   }
}

以下是訪問型別方法的語法:

type.typeMethodName()

示例

Swift 程式演示如何在結構體和類中建立和訪問型別方法。

// Defining a structure
struct AreaOfRectangle {

   // Type method using static keyword
   static func area(_ length: Int, _ breadth: Int) -> Int {
      return length * breadth 
   }
}

// Defining a class
class Area {
   // Type method using class keyword
   class func areaOfTriangle(base: Double, height: Double) -> Double {
      return (1 * base * height)/2
   }
}

// Accessing type method of AreaOfRectangle structure
let result1 = AreaOfRectangle.area(12, 10)
print("Area of rectangle is ", result1)

// Accessing type method of Area class
let result2 = Area.areaOfTriangle(base: 5, height: 15)
print("Area of triangle is ", result2)

輸出

它將產生以下輸出:

Area of rectangle is  120
Area of triangle is  37.5

示例

Swift 程式演示型別方法如何呼叫另一個型別方法和型別屬性。

// Defining a structure
struct Student {

   // Type Property
   static let name = "Mohina"
   static let totalMarks = 300

   // Type method to add marks of three major subjects
   static func add(_ Maths: Int, _ Chemistry: Int, _ Physics: Int) -> Int {
      return Maths + Physics + Chemistry
   }

   // Type method to find the percentage of three subjects marks by calling another type method
   static func percentage() -> Double {
    
      // Calling another type of method
      let finalMarks = Double(add(70, 80, 90))
        
      // Accessing type property
      let percentage = ((finalMarks / Double(totalMarks)) * 100)
      return percentage
   }
}

// Accessing a type property
print("Name of the student: \(Student.name)")

// Accessing a type method
print("Percentage: ", Student.percentage())

輸出

它將產生以下輸出:

Name of the student: Mohina
Percentage:  80.0
廣告