title: Swift: generic tree
body: <p>I am trying to make a generic tree in swift. The code I have compiles, but it gets stuck while running. The node refers to itself via its parent and children properties, like any tree should. But these make swift choke. So how are you supposed to represent a tree in swift using generics? I found a lot of questions and attempts from earlier beta versions, though nothing more recently.</p>
  
  <pre><code>protocol TreeNodeProtocol
  {
  typealias LeafType      : Comparable
  var representedObject   : LeafType  { get set }
  var parent                  : Self?     { get set }
  var children                : [Self]?   { get set }
  }
  
  final class TreeNode&lt;LeafType : Comparable&gt; : TreeNodeProtocol, Comparable
  {
  var parent      : TreeNode?     = nil
  var children    : [TreeNode]?   = nil
  var representedObject : LeafType
  
  init(representedObject : LeafType)
  {
      self.representedObject = representedObject
  }
  }
  
  func == &lt;LeafType: Comparable&gt; (left : TreeNode&lt;LeafType&gt;, right :    TreeNode&lt;LeafType&gt;) -&gt; Bool
  {
  return left.representedObject == right.representedObject
   }
  
  func &lt; &lt;LeafType: Comparable&gt; (left : TreeNode&lt;LeafType&gt;, right : TreeNode&lt;LeafType&gt;) -&gt; Bool
  {
   return left.representedObject &lt; right.representedObject
  }
  
  
  class Tree&lt;LeafType : Comparable&gt;
  {
    typealias TreeNodeType = TreeNode&lt;LeafType&gt;
  
    var description : String { return "a Tree" }
    var rootNodes : [TreeNodeType] = []
    func insertRootNode(node : TreeNodeType, atIndex index: Int? = nil)
    {
      let assumedIndex = index ?? rootNodes.count
      assert(assumedIndex &lt;= rootNodes.count, "Tree: index exceeds bounds")
      rootNodes.insert(node, atIndex: assumedIndex)
    }
  
  func insertRootNode(representedObject : LeafType, atIndex index: Int? = nil)
  {
      let newRootNode = TreeNodeType(representedObject: representedObject)
      let assumedIndex = index ?? rootNodes.count
      assert(assumedIndex &lt;= rootNodes.count, "Tree: index exceeds bounds")
      rootNodes.insert(newRootNode, atIndex: assumedIndex)
  }
  
  }
  
  
  let aTree = TreeNode&lt;String&gt;(representedObject: "d") //it doesn't go past this point
  println(aTree)
  </code></pre>
  
  <p>Another issue is that I can't make the Tree refer to the TreeNodeProtocol without generating compiler errors because it has an associated type.</p>