我想知道是否可能实现这样的事情。
我有一个这样的游乐场:
我有一个这样的游乐场:
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"
由于某种原因,它只有在函数未声明为协议的一部分,而是在协议的扩展中定义时才有效。去搞清楚。但它的确工作。