大佬教程收集整理的这篇文章主要介绍了数组 – 封闭平面嵌套对象?,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
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本地函数.它将嵌套对象的内容附加到结果中,然后有条件地为每个元素调用自身以添加其内容.
以上是大佬教程为你收集整理的数组 – 封闭平面嵌套对象?全部内容,希望文章能够帮你解决数组 – 封闭平面嵌套对象?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。