Swift - 協議



協議提供方法、屬性和其他需求功能的藍圖。它僅僅描述為方法或屬性的骨架,而不是實現。方法和屬性的實現可以透過定義類、函式和列舉來進一步完成。協議的遵循被定義為方法或屬性滿足協議的要求。

在 Swift 中定義協議

在 Swift 中,協議的定義與類、結構體或列舉非常相似。協議使用  **protocol**  關鍵字定義。

語法

以下是協議的語法:

protocol SomeProtocol {
   // protocol definition 
}

協議宣告在類、結構體或列舉型別名稱之後。單協議和多協議宣告都是可能的。如果定義了多個協議,則必須用逗號分隔。

struct SomeStructure: Protocol1, Protocol2 {
   // structure definition 
}

當必須為超類定義協議時,協議名稱應在超類名稱後用逗號分隔。

class SomeClass: SomeSuperclass, Protocol1, Protocol2 {
   // class definition 
}

屬性、方法和初始化器要求

協議要求任何符合型別的屬性、方法和初始化器。

**屬性要求**  - 協議用於指定特定的類型別屬性或例項屬性。它只指定型別或例項屬性,而不是指定它是儲存屬性還是計算屬性。還要指定屬性是“可獲取的”還是“可設定的”。

屬性要求由 'var' 關鍵字宣告為屬性變數。{get set} 用於在其型別聲明後宣告可獲取和可設定的屬性。可獲取的屬性在其型別聲明後用 {get} 屬性表示。

語法

以下是協議中定義屬性的語法:

protocol SomeProtocol {
   var propertyName : Int {get set}
}

**方法要求**  - 協議用於指定特定的型別方法或例項方法。它只包含定義部分,不包含花括號和主體。它允許方法具有可變引數。

語法

以下是協議中定義方法的語法:

protocol SomeProtocol {
   func methodName(parameters)
}

**可變方法要求**  - 如果要在協議中指定可變方法,則在方法定義之前使用 mutating 關鍵字。它允許結構體和列舉採用具有可變方法的協議。

語法

以下是協議中定義可變方法的語法:

protocol SomeProtocol {
   mutating func methodName(parameters)
}

初始化器要求:協議還用於指定符合型別將實現的初始化器。它只包含定義部分,就像普通的初始化器一樣,但不包含花括號和主體。我們可以指定指定的或便利的初始化器。

此外,符合協議的類或結構體必須在其初始化器的實現之前使用 required 修飾符。透過 'required' 修飾符,可以確保所有子類都對顯式或繼承的實現進行協議一致性。當子類重寫其超類初始化器要求時,由 'override' 修飾符關鍵字指定。

語法

以下是協議中定義初始化器的語法:

protocol SomeProtocol {
  init(parameters)
}

示例

Swift 程式建立一個類符合的協議。

// Protocol
protocol classa {

   // Properties
   var marks: Int { get set }
   var result: Bool { get }
   
   // Method
   func attendance() -> String
   func markssecured() -> String
}

// Protocol
protocol classb: classa {
   
   // Properties
   var present: Bool { get set }
   var subject: String { get set }
   var stname: String { get set }
}

// Class that conform Protocol
class classc: classb {
   var marks = 96
   let result = true
   var present = false
   var subject = "Swift 4 Protocols"
   var stname = "Protocols"
   
   func attendance() -> String {
      return "The \(stname) has secured 99% attendance"
   }
   
   func markssecured() -> String {
      return "\(stname) has scored \(marks)"
   }
}

// Instance of class
let studdet = classc()
studdet.stname = "Swift 4"
studdet.marks = 98

// Accessing methods and properties
print(studdet.markssecured())

print(studdet.marks)
print(studdet.result)
print(studdet.present)
print(studdet.subject)
print(studdet.stname)

輸出

它將產生以下輸出:

Swift 4 has scored 98
98
true
false
Swift 4 Protocols
Swift 4

示例

Swift 程式建立一個具有可變方法要求的協議。

// Protocol
protocol daysofaweek {
   // Mutating method
   mutating func display()
}

// Enumeration that conforms to the Protocol
enum days: daysofaweek {
   case sun, mon, tue, wed, thurs, fri, sat
    
   mutating func display() {
      switch self {
         case .sun:
            print("Sunday")
         case .mon:
            print("Monday")
         case .tue:
            print("Tuesday")
         case .wed:
            print("Wednesday")
         case .thurs:
            print("Thursday")
         case .fri:
            print("Friday")
         case .sat:
            print("Saturday")
      }
   }
}

// Instance of enumeration
var res = days.wed
res.display()

輸出

它將產生以下輸出:

Wednesday

示例

Swift 程式建立一個符合類的初始化器的協議。

// Protocol
protocol tcpprotocol {

   // Initializer
   init(no1: Int)
}

class mainClass {
   var no1: Int // local storage
   init(no1: Int) {
      self.no1 = no1 // initialization
   }
}

// Class that conform protocol 
class subClass: mainClass, tcpprotocol {
   var no2: Int
   init(no1: Int, no2 : Int) {
      self.no2 = no2
      super.init(no1:no1)
   }
   
   // Requires only one parameter for convenient method
   required override convenience init(no1: Int)  {
      self.init(no1:no1, no2:0)
   }
}

// Class instances
let obj1 = mainClass(no1: 20)
let obj2 = subClass(no1: 30, no2: 50)

print("res is: \(obj1.no1)")
print("res is: \(obj2.no1)")
print("res is: \(obj2.no2)")

輸出

它將產生以下輸出:

res is: 20
res is: 30
res is: 50

協議作為型別

協議不用於實現功能,而是用作函式、類、方法等的型別。協議可以在以下方面用作型別:

  • 函式、方法或初始化器作為引數或返回型別

  • 常量、變數或屬性

  • 陣列、字典或其他容器中的專案

示例

protocol Generator {
   associatedtype Element
   mutating func next() -> Element?
}

extension Array: Generator {
   mutating func next() -> Element? {
      guard !isEmpty else { return nil }
      return removeFirst()
   }
}

var items = [10, 20, 30]
while let x = items.next() {
   print(x)
}

for lists in [1, 2, 3].compactMap({ i in i * 5 }) {
   print(lists)
}

print([100, 200, 300])
print([1, 2, 3].map({ i in i * 10 }))

輸出

它將產生以下輸出:

10
20
30
5
10
15
[100, 200, 300]
[10, 20, 30]

使用擴充套件新增協議一致性

可以使用擴充套件來採用現有型別並使其符合新協議。可以使用擴充套件向現有型別新增新的屬性、方法和下標。

示例

protocol AgeClassificationProtocol {
   var age: Int { get }
   func ageType() -> String
}

class Person: AgeClassificationProtocol {
   let firstname: String
   let lastname: String
   var age: Int

   init(firstname: String, lastname: String, age: Int) {
      self.firstname = firstname
      self.lastname = lastname
      self.age = age
   }

   func fullname() -> String {
      return firstname + " " + lastname
   }

   func ageType() -> String {
      switch age {
         case 0...2:
            return "Baby"
         case 3...12:
            return "Child"
         case 13...19:
            return "Teenager"
         case 65...:
            return "Elderly"
         default:
            return "Normal"
        }
    }
}

let obj = Person(firstname: "Mona", lastname: "Singh", age: 10)
print("Full Name: \(obj.fullname())")
print("Age Type: \(obj.ageType())")

輸出

它將產生以下輸出:

Full Name: Mona Singh
Age Type: Child

協議繼承

Swift 允許協議從其定義的屬性繼承屬性。這類似於類的繼承,但可以選擇列出用逗號分隔的多個繼承協議。藉助協議,我們可以實現使用類無法實現的多重繼承。

語法

以下是協議繼承的語法:

protocol SomeProtocol: protocol1, protocol2 {
  // statement
}

示例

protocol ClassA {
   var no1: Int { get set }
   func calc(sum: Int)
}

protocol Result {
   func print(target: ClassA)
}

class Student2: Result {
   func print(target: ClassA) {
      target.calc(sum: 1)
   }
}

class ClassB: Result {
   func print(target: ClassA) {
      target.calc(sum: 5)
   }
}

class Student: ClassA {
   var no1: Int = 10
    
   func calc(sum: Int) {
      no1 -= sum
      print("Student attempted \(sum) times to pass")
        
      if no1 <= 0 {
         print("Student is absent for the exam")
      }
   }
}

class Player {
   var stmark: Result!
    
   init(stmark: Result) {
      self.stmark = stmark
   }
    
   func print(target: ClassA) {
      stmark.print(target: target)
   }
}

var marks = Player(stmark: Student2())
var marksec = Student()

marks.print(target: marksec)
marks.print(target: marksec)
marks.print(target: marksec)

marks.stmark = ClassB()
marks.print(target: marksec)
marks.print(target: marksec)
marks.print(target: marksec)

輸出

它將產生以下輸出:

Student attempted 1 times to pass
Student attempted 1 times to pass
Student attempted 1 times to pass
Student attempted 5 times to pass
Student attempted 5 times to pass
Student is absent for exam
Student attempted 5 times to pass
Student is absent for exam

僅限類協議

當定義協議時,如果使用者想要使用類定義協議,則應首先定義類,然後定義協議的繼承列表。

示例

protocol tcpprotocol {
   init(no1: Int)
}

class mainClass {
   var no1: Int // local storage
   init(no1: Int) {
      self.no1 = no1 // initialization
   }
}

class subClass: mainClass, tcpprotocol {
   var no2: Int
   init(no1: Int, no2 : Int) {
      self.no2 = no2
      super.init(no1:no1)
   }
   
   // Requires only one parameter for convenient method
   required override convenience init(no1: Int)  {
      self.init(no1:no1, no2:0)
   }
}

let res = mainClass(no1: 20)
let obj = subClass(no1: 30, no2: 50)

print("res is: \(res.no1)")
print("res is: \(obj.no1)")
print("res is: \(obj.no2)")

輸出

它將產生以下輸出:

res is: 20
res is: 30
res is: 50

協議組合

Swift 允許使用協議組合同時呼叫多個協議。我們可以使用協議組合將多個協議組合到單個需求中。它不定義任何新的協議型別,而只使用現有的協議。

在協議組合中,我們可以根據需要指定任意數量的協議,其中每個協議都用按位與符號 (&) 分隔。它還可以包含一個類型別,我們可以用它來指定超類。

語法

protocol<SomeProtocol & AnotherProtocol>

示例

protocol StName {
   var name: String { get }
}

protocol Stage {
   var age: Int { get }
}

struct Person: StName, Stage {
   var name: String
   var age: Int
}

// Protocol Composition
func printCelebrator(celebrator: StName & Stage) {
   print("\(celebrator.name) is \(celebrator.age) years old")
}

let studName = Person(name: "Priya", age: 21)
printCelebrator(celebrator: studName)

let stud = Person(name: "Rehan", age: 29)
printCelebrator(celebrator: stud)

let student = Person(name: "Roshan", age: 19)
printCelebrator(celebrator: student)

輸出

它將產生以下輸出:

Priya is 21 years old
Rehan is 29 years old
Roshan is 19 years old

檢查協議一致性

協議一致性由 'is' 和 'as' 運算子測試,類似於型別轉換。

  • 'is' 運算子如果例項符合協議標準則返回 true,如果不符合則返回 false。

  • 'as?' 版本的向下轉換運算子返回協議型別的可選值,如果例項不符合該協議,則此值為 nil。

  • 'as' 版本的向下轉換運算子強制向下轉換為協議型別,如果向下轉換不成功,則會觸發執行時錯誤。

示例

import Foundation
@objc protocol rectangle {
   var area: Double { get }
}

@objc class Circle: rectangle {
   let pi = 3.1415927
   var radius: Double
   var area: Double { return pi * radius * radius }
   init(radius: Double) { self.radius = radius }
}

@objc class result: rectangle {
   var area: Double
   init(area: Double) { self.area = area }
}

class sides {
   var rectsides: Int
   init(rectsides: Int) { self.rectsides = rectsides }
}
let objects: [AnyObject] = [Circle(radius: 2.0),result(area: 198),sides(rectsides: 4)]

for object in objects {
   if let objectWithArea = object as? rectangle {
      print("Area is \(objectWithArea.area)")
   } else {
      print("Rectangle area is not defined")
   }
}

輸出

它將產生以下輸出:

Area is 12.5663708
Area is 198.0
Rectangle area is not defined
廣告