0

I have been trying to find a struct inside the list of nested structs. Can anyone help me on this?

struct Places: PlacesProtocol {
    private(set) var id: String
    private(set) var name: String
    private(set) var childPlaces: [PlacesProtocol]?

    init(json: JSON) {
        self.name = json[“Name”]
        self.id = json[“Id”]
        self. childPlaces = json[“ChildPlaces”].arrayValue.map { Places(json: $0) }
    }

JSON:

{
    "Id": "1",
    "Name": "Place 1",
    "ChildPlaces": [{
        "Id": "12",
        "Name": "Place 2",
        "ChildPlaces": [{
            "Id": "123",
            "Name": "Place 3",
            "ChildPlaces": [{
                "Id": "1234",
                "Name": "Place 4",
                "ChildPlaces": null
            }]
        }, {
            "Id": "13",
            "Name": "Place 5",
            "ChildPlaces": null
        }]
    }]
}

I have tried this:

nestedStruct.filter { $0.id == "13" }

I am able to parse this JSON in to the nested structure and I am trying to find a struct with Id. I have tried filter but it just filters only the first layer of the nested struct. Is there a way I can build recursive filter to find the struct which is deep inside the nested struct.

2
  • I would advise against an optional array property in this case. If there are no places, just use an empty array. It doesn't allocate a buffer on the heap until it needs to store any elements, so it doesn't take up any extra resources. It's easier to work with (e.g. can be iterated directly) Commented Jan 7, 2018 at 3:47
  • What is private(set) for? If you want a constant declare the members as let Commented Jan 7, 2018 at 6:03

1 Answer 1

2

You could use a recursive function to perform a depth first search. Here's a rough example:

extension Place {

    depthFirstSearch(where closure: (Place) -> Bool) -> Place? {
        if closure(self) { return self }
        else {
            return self.chlidPlaces.first(where: { 
                $0.depthFirstSearch(where: closure)
            })
        }
    }
}


let placeID13 = mainPlace.depthFirstSearch(where: { $0.id == "13" })
Sign up to request clarification or add additional context in comments.

2 Comments

I have tried this and getting this error. Cannot convert value of type 'Place?' to closure result type 'Bool' @Alexander
@Vijay Not sure how you expect us to be able to help you without a concrete test case to work with.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.