Implementing recursive generator for simple tree structure in Swift

前端 未结 3 564
半阙折子戏
半阙折子戏 2021-01-13 18:36

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

3条回答
  •  抹茶落季
    2021-01-13 19:23

    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.

提交回复
热议问题