加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 06:02:18 所属栏目:百科 来源:网络整理
导读:我想知道是否可能实现这样的事情。 我有一个这样的游乐场: protocol Foo { func testPrint()}extension Foo { func testPrint() { print("Protocol extension call") }}struct Bar: Foo { func testPrint() { // Calling self or super go call default imp
我想知道是否可能实现这样的事情。
我有一个这样的游乐场:
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"

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读