Oleg Bizin
Oleg Bizin

Reputation: 169

How to iterate nested dictionaries with unknown numbers of nesting levels in swift?

I parse comments from web page and I get an arrays of nested dictionaries. So, data have typical nested structure of comments. Some of them have answers, some of them not. Some answers have comments too. Just like in scheme:

comment1
comment1
   comment2
   comment2
     comment3
       comment4
         comment5
       comment4
   comment2
comment1
comment1
   comment2
comment1

I know how to iterate through 2 or 3 levels of nesting with for...in statement, but I have no idea how to do it when number of nesting levels is unknown.

Basically, I need to count all nested dict's for higher levels (comment1 in scheme, for second comment1 it would be 7) and delete "wrong" dictionaries after parsing in each level. Please, help.

Update As newbie in iOS development I show my dict structure as picture. Sorry for that, but I don't know how copy from Debag area with formatting dict

Upvotes: 2

Views: 2357

Answers (2)

Si Te Feng
Si Te Feng

Reputation: 300

You can checkout the pseudocode below. It should give you the general idea of using a stack to accomplish the task

let dict = [String: AnyObject]()

let stack: Array<AnyObject>
stack.append(dict)

while stack.count != 0 {

        let comment = stack.popLast() as? [String: AnyObject]

        if value == nil {
            comment = currDict[i] as! MyObject
            print("value: \(comment)")
            // Do other stuff
        }  

        for item in comment.allValues() {
            stack.append(item)
        }
    }
}

Upvotes: 0

Moriya
Moriya

Reputation: 7906

You could do this recursively. Something like this:

func recursivelyAddComments(commentData: [String: AnyObject]) -> Comment {

    //Init with the standard data for comment
    let comment = Comment()

    //recursivly add nested comments, calling the property with the nested array for "answers"
    if let answersData = commentData["answers"] as? [String:AnyObject]{
        for answerData in answersData {
            if let answer = recursivelyAddComments(answerData){
                 comment.answers.append(answer)
            }
        }
    }

    return comment
}

So first the function creates the comment from the related data, then it parses every item in the array containing the answer comments, by calling itself with their data.

Upvotes: 3

Related Questions