Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

arrays - Closures to flat nested objects?

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]?
}

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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

First, I would highly recommend making the type of subObjects be non-optional. There's rarely a reason for optional arrays. Do you really need to distinguish between "no array" and "an empty array?" This is very uncommon. If you make subObjects just be an array, you can write what you're describing as a simple recursive function:

func flattenMyObjects(myObjects: [MyObject]) -> [MyObject] {
    return myObjects.flatMap { (myObject) -> [MyObject] in
        var result = [myObject]
        result.appendContentsOf(flattenMyObjects(myObject.subObjects))
        return result
    }
}

If you need it to be optional, the changes are minor (you'll need to add an if-let or something similar).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...