Swift协议的动态、静态派发

2017-10-06  本文已影响0人  四月白绵羊

在Swift中协议具有强大的功能。通过拓展,不仅能在协议中添加已于方法的具体实现,还能添加新的方法。

通过协议拓展来增加代码和继承的优势:

  1. 不需要强制继承某一个父类。
  2. 可以让已经存在的类型遵循协议。
  3. 协议可以用于类,也可以用于结构体和枚举。
  4. 使用协议,不用在乎super方法的调用。

For example:

protocol Fruit{
    func ripe()
}
extension Fruit{
    func ripe(){
        print ("Fruit ripe.")
    }
    func name(){
        print("Fruit")
    }
}
struct Banana : Fruit{
    func ripe(){
        print ("Banana ripe.")
    }
    func name(){
        print("Banana")
    }
}

Based on the definition, we call the methods.

let a : Fruit = Banana()
let b : Banana = Banana()
a.ripe()
b.ripe()
a.name()
b.name()

The output should be:

Banana ripe
Banana ripe
Fruit
Banana

由于name方法并没有在协议中定义,属于静态派发。所以即便a的实际类型是Banana,但是并不会去调用Banana中name方法。

上一篇 下一篇

猜你喜欢

热点阅读