我开始学习闭包,并希望在我正在开发的项目中实现它们,我想要一些帮助.
我有一个类定义如下:
class MyObject { var name: String? var type: String? var subObjects: [MyObject]? }
我想使用闭包或更高级的函数(像flatMap这样的东西)来展平[MyObject]并将所有MyObject和subOjects连接成一个数组.
我尝试使用[MyObject] .flatMap(),但此操作不返回嵌套的子对象.
展平递归类结构的一种方法是使用递归函数.
这是我们想要展平的课程:
public class nested { public let n : Int public let sub : [nested]? public init(_ n:Int,_ sub:[nested]?) { self.n = n self.sub = sub } }
以下是演示如何完成此操作的函数:
func test() { let h = [ nested(1,[nested(2,nil),nested(3,nil)]),nested(4,nested(5,[nested(6,nested(7,[nested(8,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本地函数.它将嵌套对象的内容附加到结果中,然后有条件地为每个元素调用自身以添加其内容.