![](/img/trans.png)
[英]How to make a protocol extend another protocol and provide default implementation for it in Swift?
[英]How the call the default implementation code in protocol in swift?
我在协议扩展中给出了一些默认的实现代码。 但是如何在确认协议的类中调用此指定代码。 这是一个例子:
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."
协议更像是编译时保证类型具有某些方法和属性的保证。 通过将实现注入协议的采用者,默认实现会为此增加另一层复杂性。 我没有掌握Swift的源代码的技能,但是我认为当采用者提供其自己的实现时,默认实现被遮盖了,无法将其取回。
一种解决方法是在协议中添加一个具有不同名称的方法,该方法提供默认实现,并且可以由任何采用者调用:
protocol ImplementedProtocol {
func printInfo()
func defaultPrintInfo()
}
extension ImplementedProtocol where Self: BaseClass {
func printInfo() {
defaultPrintInfo()
}
func defaultPrintInfo() {
print("Hello! This is ImplementedProtocol")
}
}
class SuperClass: BaseClass, ImplementedProtocol {
func printInfo() {
self.defaultPrintInfo()
print("Hello! This is SuperClass")
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.