使用默认参数解密Swift协议扩展

所以我们可以说

  • 如果变量推断类型为Protocol ,则将始终调用该方法的动态实现。
  • 否则 ,将调用该方法的协议实现, 除非该方法不覆盖默认参数。

我与您分享了所有这些情况的操场片段:

protocol TheProtocol { 
func method1(text: String)
}

extension TheProtocol {
func method1(text: String = "default1") {
print("Called method1 from TheProtocol: \(text)")
}
func method2(text: String = "default2") {
print("Called method2 from TheProtocol: \(text)")
}
}

struct Struct1: TheProtocol {
func method1(text: String = "default1") {
print("Called method1 from struct 1: \(text)")
}

func method2(text: String = "default2") {
print("Called method2 from struct 1: \(text)")
}
}

print("s1 is of type Struct1")
let s1 = Struct1()
s1.method1()
s1.method1(text: "CUSTOM")
s1.method2()
s1.method2(text: "CUSTOM")

print("s1 is of type TheProtocol")
let s2: TheProtocol = Struct1()
s2.method1()
s2.method1(text: "CUSTOM")
s2.method2()
s2.method2(text: "CUSTOM")

它产生以下输出:

 s1 is of type Struct1 
Called method1 from struct 1: default1
Called method1 from struct 1: CUSTOM
Called method2 from struct 1: default2
Called method2 from struct 1: CUSTOM
s1 is of type TheProtocol
Called method1 from TheProtocol: default1
Called method1 from struct 1: CUSTOM
Called method2 from TheProtocol: default2
Called method2 from TheProtocol: CUSTOM

与上面共享的图一致。

结论

带有默认参数的Swift协议扩展方法乍一看似乎有些不清楚的行为,您可能会注意到您的某些扩展或实现方法从未被调用过,并且如果您到了本文的结尾,您可能会遇到这种情况。问题,我希望在看完上图之后,现在至少您的某些疑虑消失了。