美文网首页
Protocol Extension 协议扩展

Protocol Extension 协议扩展

作者: fordring2008 | 来源:发表于2017-02-04 09:35 被阅读28次

    // 原始协议

    protocol MyProtocol {

    func method()

    }

    // 对原有协议进行扩展实现。 通过提供 protocol 的 extension, 我们为 protocol 提供了默认实现,相当于将 protocol 中的方法设定为了 optional

    extension MyProtocol {

    func method(){

    print("Called")

    }

    }

    // 这个结构体实现了 MyProtocol 协议

    struct MyStruct: MyProtocol {

    }

    MyStruct().method()  // 输出 Called

    protocol A2 {

    func method1() -> String

    }

    // 对协议进行原有的方法进行扩展并实现,并且添加了一个方法并实现

    extension A2 {

    func method1() -> String {

    return "hi"

    }

    func method2() -> String {

    return "hi"

    }

    }

    struct B2: A2 {

    func method1() -> String {

    return "hello"

    }

    func method2() -> String {

    return "hello"

    }

    }

    let b2 = B2()

    b2.method1()      //  hello

    b2.method2()      //  hello

    let a2 = b2 as A2

    a2.method1()      //  hello

    a2.method2()      //  hi

    /*

    如果类型推断得到的是实际的类型

    > 那么类型的实现将被调用,如果类型中没有实现的方法,那么协议扩展中的默认实现将被调用

    如果类型推断得到的是协议,而不是实际类型

    > 并且方法在协议中进行了定义,那么类型中的实现将被调用。如果类型中没有实现,那么协议扩展中的默认实现将被调用

    > 否则(也就是方法没有在协议中定义),扩展中的默认实现将被调用 (输出 hi)

    */

    相关文章

      网友评论

          本文标题:Protocol Extension 协议扩展

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