title: How can I reduce boilerplate with the visitor pattern in Swift?
body: <p>I am implementing the visitor pattern in Swift 2.2 for a project at work.</p>
  
  <p>So that I don't have to boil down my source code and to save me some time I will use an <a href="https://github.com/ochococo/Design-Patterns-In-Swift#-visitor">example of visitor pattern in swift by Oktawian Chojnacki</a>.</p>
  
  <pre><code>protocol PlanetVisitor {
      func visit(planet: PlanetAlderaan)
      func visit(planet: PlanetCoruscant)
      func visit(planet: PlanetTatooine)
  }
  
  protocol Planet {
      func accept(visitor: PlanetVisitor)
  }
  
  class PlanetAlderaan: Planet {
      func accept(visitor: PlanetVisitor) { visitor.visit(self) }
  }
  class PlanetCoruscant: Planet {
      func accept(visitor: PlanetVisitor) { visitor.visit(self) }
  }
  class PlanetTatooine: Planet {
      func accept(visitor: PlanetVisitor) { visitor.visit(self) }
  }
  
  class NameVisitor: PlanetVisitor {
      var name = ""
  
      func visit(planet: PlanetAlderaan)  { name = "Alderaan" }
      func visit(planet: PlanetCoruscant) { name = "Coruscant" }
      func visit(planet: PlanetTatooine)  { name = "Tatooine" }
  }
  </code></pre>
  
  <p>The problem I have been trying to solve is to reduce the boilerplate on each class that derives from <code>Planet</code>.
  As you can see they all have same function duplicated <code>func accept(visitor: PlanetVisitor) { visitor.visit(self) }</code>.</p>
  
  <p>I have tried putting a default implementation on the <code>Planet</code> protocol and implementing it on a base class and Swift does not seem to allow it due to compile time overload resolution. </p>
  
  <p>Examples:</p>
  
  <p>Default Implementation on Protocol:</p>
  
  <pre><code>extension Planet {
      func accept(visitor: PlanetVisitor) { visitor.visit(self) }
  }
  </code></pre>
  
  <p>Base Class:</p>
  
  <pre><code>class PlanetBase: Planet {
      func accept(visitor: PlanetVisitor) { visitor.visit(self) }
  }
  
  class PlanetAlderaan: PlanetBase {}
  class PlanetCoruscant: PlanetBase {}
  class PlanetTatooine: PlanetBase {}
  </code></pre>
  
  <p>Does anyone know of a way that the <code>accept</code> function could be made generic and applied automatically to each concrete class that derives from <code>Planet</code>? It is not a critical issue but it is a great puzzle!</p>