coj*_*joj 75 oop protocols swift swift2
我想知道是否有可能实现这样的目标.
我有一个像这样的游乐场:
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()
Run Code Online (Sandbox Code Playgroud)
我可以提供一个默认实现,extension但如果Bar需要默认实现中的所有内容以及其他内容,该怎么办?
它在某种程度上类似于调用es中的super.方法class来满足实现每个属性等的要求,但我认为没有可能实现相同的structs.
Aar*_*sen 86
我不知道你是否还在寻找答案,但是这样做的方法是从协议定义中删除函数,将对象转换为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"
Run Code Online (Sandbox Code Playgroud)
由于某种原因,只有在函数未被声明为协议的一部分时才会起作用,但是在协议的扩展中定义了该函数.去搞清楚.但它确实有效.
小智 9
您对这种解决此问题的方式有何看法?
protocol Foo {
func testPrint()
}
extension Foo {
func testPrint() {
defaultTestPrint()
}
func defaultTestPrint() {
print("Protocol extension call")
}
}
struct Bar: Foo {
func testPrint() {
// Calling self or super go call default implementation
defaultTestPrint()
print("Call from struct")
}
}
let sth = Bar()
sth.testPrint()
Run Code Online (Sandbox Code Playgroud)
好吧,你可以创建一个符合协议的嵌套类型,实例化它,并在那个上调用方法(无论你无法访问类型的数据都无关紧要,因为协议扩展中的实现无论如何都无法引用它).但这不是我称之为优雅的解决方案.
struct Bar: Foo {
func testPrint() {
// Calling default implementation
struct Dummy : Foo {}
let dummy = Dummy()
dummy.testPrint()
print("Call from struct")
}
}
Run Code Online (Sandbox Code Playgroud)