Difference between using Generic and Protocol as type parameters, what are the pros and cons of implement them in a function Difference between using Generic and Protocol as type parameters, what are the pros and cons of implement them in a function swift swift

Difference between using Generic and Protocol as type parameters, what are the pros and cons of implement them in a function


There is actually a video from this year's WWDC about that (it was about performance of classes, structs and protocols; I don't have a link but you should be able to find it).

In your second function, where you pass a any value that conforms to that protocol, you are actually passing a container that has 24 bytes of storage for the passed value, and 16 bytes for type related information (to determine which methods to call, ergo dynamic dispatch). If the passed value is now bigger than 24 bytes in memory, the object will be allocated on the heap and the container stores a reference to that object! That is actually extremely time consuming and should certainly be avoided if possible.

In your first function, where you use a generic constraint, there is actually created another function by the compiler that explicitly performs the function's operations upon that type. (If you use this function with lots of different types, your code size may, however, increase significantly; see C++ code bloat for further reference.) However, the compiler can now statically dispatch the methods, inline the function if possible and does certainly not have to allocate any heap space. Stated in the video mentioned above, code size does not have to increase significantly as code can still be shared... so the function with generic constraint is certainly the way to go!


Now we have two protocol below:

protocol A {    func sometingA()}protocol B {    func sometingB()}

Then the parameter need to conform to both A and B.

//Generic solutionfunc methodGeneric<T:A>(t:T)where T:B {    t.sometingA()    t.sometingB()}//we need protocol C to define the parameter typeprotocol C:A,B {}//Protocol solutionfunc methodProtocol(c:C){    c.sometingA()    c.sometingB()}

It seems that nothing is wrong but when we define a struct like this:

struct S:A,B {    func sometingB() {        print("B")    }    func sometingA() {        print("A")    }}

The methodGeneric works but we need to change struct S:A,B to struct S:C to make methodProtocol work. Some questions:

  1. Do we really need protocol C?
  2. Why not would we write like func method(s:S)?

You could read more about this in the Generic Doc for additional information .