我已经给出了协议扩展中的一些默认实现代码。但是如何在类中调用这个指定的代码来确认协议。下面是一个例子:如何在swift中调用protocol中的默认实现代码?
class BaseClass {}
protocol ImplementedProtocol {
func printInfo()
}
extension ImplementedProtocol where Self: BaseClass {
func printInfo() {
print("Hello! This is ImplementedProtocol")
}
}
class SuperClass: BaseClass, ImplementedProtocol {
func printInfo() {
// I should do sth here.
print("Hello! This is SuperClass")
}
}
class SubClass: SuperClass {
override func printInfo() {
super.printInfo()
print("This is SubClass")
}
}
let a = SubClass()
a.printInfo() // I get "Here is SuperClass. Here is SubClass."
// But I want "Here is ImplementedProtocol. Here is SuperClass. Here is SubClass."
我相信[这个问题](HTTP://计算器.com/questions/32602712/calling-protocol-default-implementation-from-regular-method)可能对你有所帮助。 –
好吧,当我尝试在SuperClass中使用'(self as ImplementedProtocol).printInfo()'这样的代码时,它只是在SubClass中调用'printInfo()'。它会导致无限循环。 –