title: Implementing recursive generator for simple tree structure in Swift
body: <p>I have a simple tree structure in memory based on an XML document and I am trying to write a recursive generator to support <code>SequenceType</code>, but I am stuck on how to actually do this.</p>
  
  <p>Here was my first attempt:</p>
  
  <pre><code>@objc public class XMLNode: NSObject, SequenceType {
      public weak var parentNode: XMLNode?
      public var nodeName: String
      public var attributes: [String: String]
      public var childNodes = [XMLNode]()
  
      public func generate() -&gt; AnyGenerator&lt;XMLNode&gt; {
          var childGenerator = childNodes.generate()
          var returnedSelf = false
  
          return anyGenerator {
              let child = childGenerator.next()
  
              if child != nil {
                  // I need to somehow recurse on child here
  
                  return child
              } else if !returnedSelf {
                  returnedSelf = true
                  return self
              } else {
                  return nil
              }
          }
      }
  }
  </code></pre>
  
  <p>Since <code>childNodes</code> is an array, I'm calling its own built-in <code>generate()</code> function to create a generator on the child nodes and iterating it, and then returning <code>self</code> at the end. The problem is it's not recursing on each child, so it only ever goes one level deep. I can't figure out how to combine two generators in that way.</p>
  
  <p>I'm having a hard time wrapping my head around how to do this! What do I need to do to make a recursive generator?</p>