如何调用swift协议中的默认实现代码?

如何调用swift协议中的默认实现代码?,swift,syntax,Swift,Syntax,我已经给出了协议扩展中的一些默认实现代码。但是如何在确认协议的类中调用此指定代码。以下是一个例子: class BaseClass {} protocol ImplementedProtocol { func printInfo() } extension ImplementedProtocol where Self: BaseClass { func printInfo() { print("Hello! This is ImplementedProtocol"

我已经给出了协议扩展中的一些默认实现代码。但是如何在确认协议的类中调用此指定代码。以下是一个例子:

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")
    }
}

协议更像是编译时保证,类型具有特定的方法和属性。默认实现通过向协议的采纳者注入一个实现,增加了另一层复杂性。我不具备浏览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")
    }
}

我相信这可能会对您有所帮助。当我尝试在超类中使用类似于
(self as ImplementedProtocol).printInfo()
的代码时,它只调用子类中的
printInfo()
。它会导致无限循环。我相信这可能会对您有所帮助。好吧,当我尝试在超类中使用类似于
(self-as-ImplementedProtocol).printInfo()
的代码时,它只调用子类中的
printInfo()
。由于我的想法不是swift中首选的代码样式,我决定将实现从
ImplementedProtocol
移动到
SuperClass
,尽管我必须为继承自
ImplementedProtocol
的类实现类似的代码。谢谢你的回答。由于我的想法不是swift中首选的代码样式,我决定将实现从
ImplementedProtocol
移动到
SuperClass
,尽管我必须为继承自
ImplementedProtocol
的类实现类似的代码。谢谢你的回答。