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

你可能感兴趣的:(swift 类型继承协议后,方法调用规则测试)