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需要一切在默认实现加上额外的东西?
我不知道你是否仍然在寻找这个答案,但方法是从协议定义中删除该函数,将对象转换为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" 由于某种原因,它只有在函数未声明为协议的一部分,而是在协议的扩展中定义时才有效。去搞清楚。但它的确工作。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |