swift中当原类型中的方法和遵守的protocol中方法方法重
2021-10-13 本文已影响0人
梁森的简书
0.method.jpg
如上图所示。
需要注意的是,当变量推断为协议的时候,且协议中未定义该方法,那么会调用协议扩展中实现的该方法(如果协议扩展中未实现该方法会编译报错)。
其他情况,只要原类型中实现了该方法就调用原类型中的该方法。
代码:
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")
}
}
func testProtocolAnd() {
let s1 = Struct1()
s1.method1()
s1.method2()
s1.method3()
print("\n-----------------\n")
let s2:TheProtocol = Struct1() // s2 会被推断为协议对象
s2.method1()
s2.method2() // 如果在 extension TheProtocol 未实现该方法,编译报错 (protocol中未定义该方法)
s2.method3()
print("\n-----------------\n")
}
打印结果:
called method1 from Struct1
called method2 from Struct1
Called method3 from TheProtocol
-----------------
called method1 from Struct1
Called method2 from TheProtocol
Called method3 from TheProtocol
-----------------