深入解析Swift语言中的协议

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


当我们使用 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() {
   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 运行上面的程序,得到以下结果。

 


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 {