title: Difference between using Generic and Protocol as type parameters, what are the pros and cons of implement them in a function
body: <p>Since Swift allows us using both Protocol and Generic as parameter types in a function, the scenario below has come into my mind:</p>
  
  <pre><code>protocol AProtocol {
      var name: String{ get }
  }
  
  class ClassA: AProtocol {
      var name = "Allen"
  }
  
  func printNameGeneric&lt;T: AProtocol&gt;(param: T) {
      print(param.name)
  }
  
  func printNameProtocol(param: AProtocol) {
      print(param.name)
  }
  </code></pre>
  
  <p>The first function uses generic as parameter type with a type constraint, and the second function uses protocol as the parameter type directly. However, these two functions can have the same effect, which is the point confusing me. So my questions are:</p>
  
  <ol>
  <li><p>What are the specific scenarios for each of them (or a case which can only be done by the specific one, but not another)?</p></li>
  <li><p>For the given case, both functions turn out the same result. Which one is better to implement (or the pros and cons of each of them)?</p></li>
  </ol>
  
  <p><a href="https://developer.apple.com/videos/play/wwdc2016/416/" rel="noreferrer">This great talk</a> has mentioned <strong>generic specialization</strong>, which is a optimization that turn the way of function dispatching from <strong>dynamic dispatching</strong> (function with <strong>non-generic parameters)</strong> to <strong>static dispatching</strong> or <strong>inlining</strong> (function with <strong>generic parameters)</strong>. Since <strong>static dispatching</strong> and <strong>inlining</strong> are less expensive in contrast with <strong>dynamic dispatching</strong>, to implement functions with generic can always provide a better performance.</p>
  
  <p>@Hamish also gave great information in <a href="https://stackoverflow.com/questions/38446487/what-is-the-in-practice-difference-between-generic-and-protocol-typed-function-p">this post</a>, have a look for more information.</p>
  
  <p>Here is a new question came to me:</p>
  
  <pre><code>struct StructA: AProtocol {
      var a: Int
  }
  
  struct StructB: AProtocol {
      var b: Int
  }
  
  func buttonClicked(sender: UIButton) {
      var aVar: AProtocol
  
      if sender == self.buttonA
      {
          aVar = StructA(a: 1)
      }
      else if sender == self.buttonA
      {
          aVar = StructB(b: 2)
      }
  
      foo(param: aVar)
  }
  
  func foo&lt;T: AProtocol&gt;(param: T) {
      //do something
  }
  </code></pre>
  
  <ol start="3">
  <li>If there are several types conform to a Protocol, and are pass in to a generic function in different conditions dynamically. As shown above, pressing different buttons will pass different types(StructA or StructB) of parameter into function, would the generic specialization still work in this case?</li>
  </ol>