深入解析Swift语言中的协议

2020-01-08 22:38:09王旭

marks.print(marksec)
marks.print(marksec)
marks.print(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)

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


当我们使用 playground 运行上面的程序,得到以下结果。

 


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