Swift 如何在具有“associatedtype”的协议中重用函数?
考虑以下情况:Swift 如何在具有“associatedtype”的协议中重用函数?,swift,swift-protocols,code-reuse,swift-extensions,associated-types,Swift,Swift Protocols,Code Reuse,Swift Extensions,Associated Types,考虑以下情况: protocol P { associatedtype T = String func f() } extension P { func f() {print("I want to reuse this function")} } class A: P { func f() { (self as P).f() // can't compile print("do more thing
protocol P {
associatedtype T = String
func f()
}
extension P {
func f() {print("I want to reuse this function")}
}
class A: P {
func f() {
(self as P).f() // can't compile
print("do more things.")
}
}
如果没有关联类型
,则表达式(self as p).f()
正常。
当
P
具有associatedType
时,是否有一种方法可以重用P.f()
?我认为这是不可能的。但有一个简单的解决办法:
protocol P {
associatedtype T = String
func f()
}
extension P {
func f() {g()}
func g() {print("I want to reuse this function")}
}
class A: P {
func f() {
self.g() // no problem with compilation, calls protocol's implementation
print("do more things.")
}
}
只有在
扩展名P
中修改f()
的代码时,这才有效@蘇哲聖 不,修改类A的代码就足够了。这里的问题是,您试图让协议和采用程序的行为类似于超类和子类,这很愚蠢。如果您希望能够调用扩展名的f
,请不要用另一个f
来“覆盖”它。即使没有associatedtype
,调用(self as P).f()
也会在运行时导致无限循环错误。