2015-11-04 76 views
2

我解析网页的评论,我得到一个嵌套 字典的数组。因此,数据具有典型的评论嵌套结构。他们中的一些人有答案,其中一些不是。有些答案也有评论。就像在方案:如何在swift中迭代嵌套字典的未知嵌套层次数?

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

我知道如何通过2个或3个级别与嵌套... in语句的迭代,但我不知道该怎么做时,嵌套层数是未知的。

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

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

+0

请显示您的实际字典结构的一个小例子。谢谢。 – Moritz

+0

@ eric-d,我用topfunky/hpple解析器解析HTML数据,所以它有点难读 –

+0

你可以用虚假内容显示一个例子。 :)我的观点是:在你的关于字典结构的问题中,我没有看到任何嵌套的字典结构,只是一堆行,所以它很难提供帮助。 – Moritz

回答

3

你可以递归地做到这一点。事情是这样的:

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 
} 

所以首先函数创建从相关数据的评论,然后将其解析每个项目包含答案的意见数组中,通过调用本身与他们的数据。

0

您可以检出下面的伪代码。它应该给你使用堆栈来完成任务的一般想法

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) 
     } 
    } 
}