swift – 从常规方法调用协议默认实现

我想知道是否可能实现这样的事情。
我有一个这样的游乐场:
protocol Foo {
    func testPrint()
}

extension Foo {
    func testPrint() {
        print("Protocol extension call")
    }
}

struct Bar: Foo {
    func testPrint() {
        // Calling self or super go call default implementation
        self.testPrint()
        print("Call from struct")
    }
}


let sth = Bar()
sth.testPrint()

我可以在扩展中提供一个默认实现,但如果Bar需要一切在默认实现加上额外的东西?
它在某种程度上类似于调用super。类中的方法来满足实现每个属性的需求等,但是我看不到使用struct实现相同的可能性。

我不知道你是否仍然在寻找这个答案,但方法是从协议定义中删除该函数,将对象转换为Foo,然后调用它的方法:
protocol Foo { 
    // func testPrint() <- comment this out or remove it
}

extension Foo {
    func testPrint() {
        print("Protocol extension call")
    }
}

struct Bar: Foo {
    func testPrint() {
        print("Call from struct")
        (self as Foo).testPrint() // <- cast to Foo and you'll get the  default
                                  //    function defined in the extension
    }
}

Bar().testPrint()

// Output:    "Call from struct"
//            "Protocol extension call"

由于某种原因,它只有在函数未声明为协议的一部分,而是在协议的扩展中定义时才有效。去搞清楚。但它的确工作。

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...