Closures to flat nested objects?

前端 未结 2 1576
悲&欢浪女
悲&欢浪女 2020-12-21 14:55

I\'m starting to learn about closures and want to implement them in a project I\'m working on and I\'d like some help.

I have a class defined as follows:

         


        
2条回答
  •  时光说笑
    2020-12-21 15:24

    One approach to flattening a recursive class structure is with a recursive function.

    Here is the class that we would like flattened:

    public class Nested {
        public let n : Int
        public let sub : [Nested]?
        public init(_ n:Int, _ sub:[Nested]?) {
            self.n = n
            self.sub = sub
        }
    }
    

    Here is the function that demonstrates how this could be done:

    func test() {
        let h = [
            Nested(1, [Nested(2, nil), Nested(3, nil)])
        ,   Nested(4, nil)
        ,   Nested(5, [Nested(6, nil), Nested(7, [Nested(8, nil), Nested(9, nil)])])
        ]
        func recursiveFlat(next:Nested) -> [Nested] {
            var res = [Nested]()
            res.append(next)
            if let subArray = next.sub {
                res.appendContentsOf(subArray.flatMap({ (item) -> [Nested] in
                    recursiveFlat(item)
                }))
            }
            return res
        }
        for item in h.flatMap(recursiveFlat) {
            print(item.n)
        }
    }
    

    The heart of this approach is recursiveFlat local function. It appends the content of the nested object to the result, and then conditionally calls itself for each element to add their contents as well.

提交回复
热议问题