簡體   English   中英

如何快速迭代嵌套數量未知的嵌套字典?

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

我從網頁上解析評論,然后得到一系列嵌套詞典。 因此,數據具有注釋的典型嵌套結構。 其中一些有答案,有些沒有。 一些答案也有評論。 就像在方案中一樣:

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

我知道如何使用for ... in語句遍歷2或3個嵌套層,但是當嵌套層數未知時,我不知道該如何做。

基本上,我需要計算更高級別的所有嵌套dict(方案中的注釋1,第二個comment1為7),並在每個級別進行解析后刪除“錯誤的”字典。 請幫忙。

更新作為iOS開發中的新手,我將dict結構顯示為圖片。 抱歉,但是我不知道如何從Debag區域進行格式化 字典

您可以遞歸執行此操作。 像這樣:

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
}

因此,該函數首先根據相關數據創建注釋,然后通過對其自身的數據進行調用來解析包含答案注釋的數組中的每個項目。

您可以在下面簽出偽代碼。 它應該給您使用堆棧來完成任務的一般思路

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM