美文网首页
swift 类型继承协议后,方法调用规则测试

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

作者: VictorZhangWang | 来源:发表于2021-05-25 10:59 被阅读0次

测试代码:

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 类型继承协议后,方法调用规则测试

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