I have a simple tree structure in memory based on an XML document and I am trying to write a recursive generator to support SequenceType
, but I am stuck on how
While Martin's answer is certainly more concise, it has the downside of making a lot of using a lot of array/insert operations and is not particularly usable in lazy sequence operations. This alternative should work in those environments, I've used something similar for UIView
hierarchies.
public typealias Generator = AnyGenerator
public func generate() -> AnyGenerator {
var childGenerator = childNodes.generate()
var subGenerator : AnyGenerator?
var returnedSelf = false
return anyGenerator {
if !returnedSelf {
returnedSelf = true
return self
}
if let subGenerator = subGenerator,
let next = subGenerator.next() {
return next
}
if let child = childGenerator.next() {
subGenerator = child.generate()
return subGenerator!.next()
}
return nil
}
}
Note that this is preorder iteration, you can move the if !returnedSelf
block around for post order.