ios - 如何在 swift 中迭代未知数量的嵌套级别的嵌套字典?

标签 ios arrays swift dictionary

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

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

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

基本上,我需要计算更高级别的所有嵌套字典(方案中的 comment1,对于第二个 comment1 为 7),并在每个级别解析后删除“错误”字典。 请帮忙。

更新 作为 iOS 开发的新手,我将我的字典结构显示为图片。抱歉,但我不知道如何从 Debag 区域复制格式 dict

最佳答案

您可以递归地执行此操作。像这样的事情:

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
}

因此,该函数首先根据相关数据创建注释,然后通过使用其数据调用自身来解析包含答案注释的数组中的每个项目。

关于ios - 如何在 swift 中迭代未知数量的嵌套级别的嵌套字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33526326/

相关文章:

ios - 如何使用 Alamofire 制定一个良好的模式来控制多个请求依赖关系?比如request2需要request1的响应

ios - Swift:XPC 连接中断并且应用程序卡住?

ios - 表格单元格圆角边框

C++线程性能

c++ - 在C++中输入一个句子

python - python中arange的奇怪行为

ios - AVAudioplayer如何让当前时间自动更新

android - 如何更改 ListView 中一行内状态的开关状态 - React Native

ios - Google Analytics 如何理解移动项目的类别、操作和标签?

ios - IPhone景观和肖像