Swift協定


協定(Protocols)為方法,屬性和其他需求功能提供了藍圖。 它為方法或屬性骨架而不是實現。 通過定義類,函式和列舉,可以進一步完成方法和屬性的實現。 協定的一致性滿足了協定要求的方法或屬性。

語法
協定也遵循與類,結構和列舉類似的語法 -

protocol SomeProtocol {
   // protocol definition 
}

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

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

當要為超類定義協定時,協定名稱應使用逗號跟隨超類名稱。

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

屬性和方法要求

協定用於指定特定的類型別屬性或範例屬性。 它只是單獨指定型別或範例屬性,而不是指定它是儲存屬性還是計算屬性。 此外,它還用於指定屬性是gettablesettable

屬性需求由var關鍵字宣告為屬性變數。 {get/set}用於在型別宣告後宣告gettablesettable屬性。參考以下一個範例程式碼 -

protocol classa {
   var marks: Int { get set }
   var result: Bool { get }

   func attendance() -> String
   func markssecured() -> String
}

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

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)"
   }
}

let studdet = classc()
studdet.stname = "Swift 4"
studdet.marks = 98
studdet.markssecured()

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

當使用playground 執行上述程式時,得到以下結果 -

98
true
false
Swift 4 Protocols
Swift 4

變異方法要求

protocol daysofaweek {
   mutating func print()
}

enum days: daysofaweek {
   case sun, mon, tue, wed, thurs, fri, sat 
   mutating func print() {
      switch self {
         case sun:
            self = sun
            print("Sunday")
         case mon:
            self = mon
            print("Monday")
         case tue:
            self = tue
            print("Tuesday")
         case wed:
            self = wed
            print("Wednesday")
         case mon:
            self = thurs
            print("Thursday")
         case tue:
            self = fri
            print("Friday")
         case sat:
            self = sat
            print("Saturday")
         default:
            print("NO Such Day")
      }
   }
}

var res = days.wed
res.print()

當使用playground 執行上述程式時,得到以下結果 -

Wednesday

初始化器要求

Swing允許使用者初始化協定以遵循類似於普通初始化器的型別一致性。

語法

protocol SomeProtocol {
   init(someParameter: Int)
}

範例

protocol tcpprotocol {
   init(aprot: Int)
}

協定初始化程式要求的類實現

指定或便捷初始化器允許使用者初始化協定以使其標準符合保留的required關鍵字。

class SomeClass: SomeProtocol {
   required init(someParameter: Int) {
      // initializer implementation statements
   }
}

protocol tcpprotocol {
   init(aprot: Int)
}

class tcpClass: tcpprotocol {
   required init(aprot: Int) {
   }
}

當使用playground 執行上述程式時,得到以下結果 -

Wednesday

通過required修飾符確保所有子類的協定一致性,用於顯式或繼承實現。當子類重寫其超類初始化要求時,由override修飾符關鍵字指定。

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 print = subClass(no1: 30, no2: 50)

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

當使用playground 執行上述程式時,得到以下結果 -

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

作為型別的協定

它們不是在協定中實現功能,而是用作函式,類,方法等的型別。協定可以作為以下型別存取 -

  • 函式,方法或初始化為引數或返回型別
  • 常數,變數或屬性
  • 陣列,字典或其他容器作為專案

範例程式碼

protocol Generator {
   typealias members
   func next() -> members?
}

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

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

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

當使用playground 執行上述程式時,得到以下結果 -

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

新增協定與擴充套件的一致性

通過使用擴充套件,可以採用現有型別並使其符合新協定。 借助擴充套件,可以將新屬性,方法和下標新增到現有型別中。

範例程式碼

protocol AgeClasificationProtocol {
   var age: Int { get }
   func agetype() -> String
}
class Person {
   let firstname: String
   let lastname: String
   var age: Int

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

extension Person : AgeClasificationProtocol {
   func fullname() -> String {
      var c: String
      c = firstname + " " + lastname
      return c
   }
   func agetype() -> String {
      switch age {
         case 0...2:
            return "Baby"
         case 2...12:
            return "Child"
         case 13...19:
            return "Teenager"
         case let x where x > 65:
            return "Elderly"
         default:
            return "Normal"
      }
   }
}

協定繼承

Swift 4允許協定從其定義的屬性繼承屬性。它類似於類繼承,但可以選擇列出用逗號分隔的多個繼承協定。

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 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)

當使用playground 執行上述程式時,得到以下結果 -

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 print = subClass(no1: 30, no2: 50)

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

當使用playground 執行上述程式時,得到以下結果 -

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

協定組成

Swift 4允許使用協定組合一次呼叫多個協定。

語法

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
}
func print(celebrator: stname & stage) {
   print("\(celebrator.name) is \(celebrator.age) years old")
}
let studname = Person(name: "Yiibai", age: 21)
print(studname)

let stud = Person(name: "Maxsu", age: 29)
print(stud)

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

當使用playground 執行上述程式時,得到以下結果 -

Person(name: "Yiibai", age: 21)
Person(name: "Maxsu", age: 29)
Person(name: "Roshan", age: 19)

檢查協定一致性

協定一致性由isas運算子測試,類似於型別轉換。

  • 如果範例符合協定標準,則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")
   }
}

當使用playground 執行上述程式時,得到以下結果 -

Area is 12.5663708
Area is 198.0
Rectangle area is not defined