如何快速迭代嵌套数量未知的嵌套字典? [英] How to iterate nested dictionaries with unknown numbers of nesting levels in swift?

查看:143
本文介绍了如何快速迭代嵌套数量未知的嵌套字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我解析了网页中的注释,并得到了嵌套的数组字典.因此,数据具有注释的典型嵌套结构.他们中有些人有答案,有些人没有答案.一些答案也有评论.就像在方案中一样:

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

我知道如何使用for ... in语句迭代2或3个嵌套层,但是当嵌套层数未知时,我不知道该怎么做.

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.

基本上,我需要计算所有嵌套字典的更高级别(方案中的注释1,第二个注释1为7),并在每个级别进行解析后删除错误的"字典.请帮助.

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.

更新作为iOS开发中的新手,我将dict结构显示为图片.抱歉,但是我不知道如何从Debag区域进行格式化

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

推荐答案

您可以递归地执行此操作.像这样:

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.

这篇关于如何快速迭代嵌套数量未知的嵌套字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆