swift 类型继承协议后,方法调用规则测试

测试代码:

protocol TheProtocol {
    func method1()
    func method3()
}

extension TheProtocol {
    func method1() {
        print("Called method1 from TheProtocol")
    }
    func method2() {
        print("Called method2 from TheProtocol")
    }
    
    func method3() {
        print("Called method3 from TheProtocol")
    }
}

struct Struct1: TheProtocol {
    func method1() {
        print("called method1 from Struct1")
    }
    
    func method2() {
        print("called method2 from Struct1")
    }
}


let s1 = Struct1()
s1.method1()
s1.method2()
s1.method3()

print("\n-----------------\n")

let s2:TheProtocol = Struct1()
s2.method1()
s2.method2() // 如果在 extension TheProtocol 未实现该方法,编译报错
s1.method3()

print("\n-----------------\n")

结论:


image

参考:
https://www.jianshu.com/p/3b3219fb8ada
https://medium.com/ios-os-x-development/swift-protocol-extension-method-dispatch-6a6bf270ba94

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容