Call the default protocol from the default method

I am wondering if such a goal can be achieved.
I have a playground like this:

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() 

I can provide a default implementation in extension , but what if Bar needs everything there is in the default implementation plus additional things?
It is somehow like calling super. methods super. in class es to fulfill the requirement of implementing each property, etc., but I don’t see the possibility of achieving the same with structs .

+45
oop swift swift2 protocols
Sep 16 '15 at 7:51
source share
3 answers

I don’t know if you continue to search for the answer to this question, but the way to do this is to remove the function from the protocol definition, drop your object to Foo and then call the method on it:

 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" 

For some reason, it only works if the function is not declared part of the protocol, but is defined in the protocol extension. Go figure. But it works.

+52
Jan 13 '16 at 21:33
source share

Well, you can create a nested type that matches the protocol, create an instance of it and call a method on it (it doesn’t matter that you cannot access the data of the type, since the implementation inside the protocol extension cannot reference it in any case), but it doesn’t a solution that I would call elegant.

 struct Bar: Foo { func testPrint() { // Calling default implementation struct Dummy : Foo {} let dummy = Dummy() dummy.testPrint() print("Call from struct") } } 
+4
Sep 16 '15 at 11:07
source share

Thank you for message! If you put the function definition in the protocol, then when the object is passed as the protocol, it sees only the object version of the function and, since you call it inside yourself, you get a new Apple address ...

I tried this version:

 import UIKit protocol MyProc { } protocol MyFuncProc { func myFunc() } extension MyProc { func myFunc() { print("Extension Version") } } struct MyStruct: MyProc, MyFuncProc { func myFunc() { print("Structure Version") (self as MyProc).myFunc() } } (MyStruct() as MyFuncProc).myFunc() 

This gives the conclusion:

 Structure Version Extension Version 
+1
Nov 17 '16 at 0:36
source share



All Articles