封闭到平面嵌套对象? [英] Closures to flat nested objects?

查看:79
本文介绍了封闭到平面嵌套对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始学习闭包,并希望在我正在研究的项目中实现闭包,

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:

class MyObject {
var name: String?
var type: String?
var subObjects: [MyObject]?
}

我想使用闭包或更高阶的函数(想到flatMap之类的东西)来平整[MyObject]并将所有MyObjectsubOjects连接到一个数组中.

And I want to use closures or higher oder functions (something like flatMap comes to mind) to flatten an [MyObject] and joining all MyObject and subOjects into one array.

我尝试使用[MyObject].flatMap(),但是此操作不会返回嵌套的子对象.

I've tried using [MyObject].flatMap() but this operation doesn't return the nested subObjects.

推荐答案

一种平坦化递归类结构的方法是使用递归函数.

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)
    }
}

此方法的核心是recursiveFlat局部功能.它将嵌套对象的内容附加到结果中,然后有条件地为每个元素调用自身以添加其内容.

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.

这篇关于封闭到平面嵌套对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆