深入解析Swift語言中的協議_Swift

來源:互聯網
上載者:User

協議為方法,屬性和其他要求的功能提供了一個藍本。它只是描述了方法或屬性的骨架,而不是實現。方法和屬性實現還可以通過定義類,函數和枚舉完成。協議的一致性是指方法或屬性滿足協議的要求。

文法
協議也遵循類似類,結構和枚舉的文法:

複製代碼 代碼如下:

protocol SomeProtocol {
    // protocol definition
}

協議在類,結構或枚舉類型命名聲明。單個和多個協議的聲明也是可以的。如果多個協議規定,它們必須用逗號分隔。
複製代碼 代碼如下:

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

當一個協議在超類中定義,協議名稱應遵循命名在超類之後。
複製代碼 代碼如下:

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

屬性和方法的要求
協議用於指定特定類型的屬性或屬性的執行個體。它僅指定類型或執行個體屬性單獨而不是指定它是否是一個儲存或計算屬性。另外,它是用來指定的屬性是否為“可擷取'或'可設定”。

屬性要求由 “var” 關鍵字作為屬性變數聲明。 {get set} 使用它們型別宣告後聲明屬性可擷取和可設定。 可擷取是由它們的類型{get}取屬性聲明後提及。

複製代碼 代碼如下:

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 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"
studdet.marks = 98
studdet.markssecured()

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


當我們使用 playground 運行上面的程式,得到以下結果。

98truefalseSwift ProtocolsSwift

不同變形方法要求

複製代碼 代碼如下:

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
         println("Sunday")
      case mon:
         self = mon
         println("Monday")
      case tue:
         self = tue
         println("Tuesday")
      case wed:
         self = wed
         println("Wednesday")
      case mon:
         self = thurs
         println("Thursday")
      case tue:
         self = fri
         println("Friday")
      case sat:
         self = sat
         println("Saturday")
      default:
         println("NO Such Day")
      }
   }
}

var res = days.wed
res.print()


當我們使用 playground 運行上面的程式,得到以下結果。

Wednesday

初始化程式要求
Swift 允許使用者初始化協議遵循類似於正常初始化類型的一致性。

文法

複製代碼 代碼如下:

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


協議一致性保證所有子類顯式或繼承實現“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)

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


當我們使用 playground 運行上面的程式,得到以下結果。

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

協議作為類型
相反,在協議執行的功能被用作函數,類,方法等類型。

協議可以訪問作為類型:

函數,方法或初始化作為一個參數或傳回型別

常量,變數或屬性

數組,字典或其他容器作為項目

複製代碼 代碼如下:

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

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

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

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


當我們使用 playground 運行上面的程式,得到以下結果。

10203051015[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 允許協議繼承其定義的屬性的屬性。它類似於類的繼承,但用逗號分隔列舉選擇多個繼承協議。
複製代碼 代碼如下:

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(1)
   }
}

class classb: result {
   func print(target: classa) {
      target.calc(5)
   }
}

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

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

var marks = Player(stmark: student2())
var marksec = student()

marks.print(marksec)
marks.print(marksec)
marks.print(marksec)
marks.stmark = classb()
marks.print(marksec)
marks.print(marksec)
marks.print(marksec)


當我們使用 playground 運行上面的程式,得到以下結果。

Student attempted 1 times to passStudent attempted 1 times to passStudent attempted 1 times to passStudent attempted 5 times to passStudent attempted 5 times to passStudent is absent for examStudent attempted 5 times to passStudent 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)

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


當我們使用 playground 運行上面的程式,得到以下結果。

res is: 20res is: 30res 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
}

func print(celebrator: protocol<stname, stage>) {
   println("\(celebrator.name) is \(celebrator.age) years old")
}

let studname = Person(name: "Priya", age: 21)
print(studname)

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

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


當我們使用 playground 運行上面的程式,得到以下結果。

Priya is 21 years oldRehan is 29 years oldRoshan is 19 years old

檢查協議一致性
協議一致性是 is 和 as 類似於類型轉換的操作符測試。

如果一個執行個體符合協議標準,is運算子如果失敗返回false ,否則返回true。

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 {
      println("Area is \(objectWithArea.area)")
   } else {
      println("Rectangle area is not defined")
   }
}


當我們使用 playground 運行上面的程式,得到以下結果。

Area is 12.5663708Area is 198.0Rectangle area is not defined

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.