美文网首页
Swift协议的动态、静态派发

Swift协议的动态、静态派发

作者: 四月白绵羊 | 来源:发表于2017-10-06 03:04 被阅读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方法。

    相关文章

      网友评论

          本文标题:Swift协议的动态、静态派发

          本文链接:https://www.haomeiwen.com/subject/tfqmextx.html