麻豆小视频在线观看_中文黄色一级片_久久久成人精品_成片免费观看视频大全_午夜精品久久久久久久99热浪潮_成人一区二区三区四区

首頁 > 編程 > Swift > 正文

深入解析Swift語言中的協議

2020-03-09 17:52:55
字體:
來源:轉載
供稿:網友
這篇文章主要介紹了深入解析Swift語言中的協議,是Swift入門學習中的基礎知識,需要的朋友可以參考下
 

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

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

復制代碼代碼如下:

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
 


注:相關教程知識閱讀請移步到swift教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 一区二区三区在线观看国产 | 毛片免费视频观看 | 高潮激情aaaaa免费看 | 免费一级欧美在线观看视频 | 久久精品中文字幕一区二区三区 | 欧美一级特黄aaaaaaa什 | av电影在线网 | 久久激情小视频 | 亚洲成人欧美在线 | 羞羞视频免费视频欧美 | 国产宾馆3p国语对白 | 亚洲视频在线免费看 | 国产成人高潮免费观看精品 | av电影免费播放 | 91九色福利| 精品国产99久久久久久宅男i | 99精彩视频在线观看 | 天天操天天碰 | av免费在线观看免费 | 欧美a∨一区二区三区久久黄 | 久久亚洲春色中文字幕久久 | 久久久久亚洲国产精品 | 中文字幕免费在线看 | 日韩毛片在线看 | 色中色在线播放 | 日操操夜操操 | 在线成人www免费观看视频 | 国产一级毛片高清视频 | 成人男男视频拍拍拍在线观看 | 在线a毛片免费视频观看 | 欧美激情首页 | 91性视频 | 女人解衣喂奶电影 | 在线看免电影网站 | 久久久www成人免费精品 | 欧美中文字幕一区二区 | 精品国产一区二区三区在线观看 | 欧美一级黄视频 | 国产精品视频导航 | 亚洲午夜在线视频 | 国产精品久久久久久久久久了 |