我解析网页中的评论,得到一个嵌套数组 字典。因此,数据具有典型的注释嵌套结构。有些人有答案,有些人没有。有些答案也有评论。就像方案中一样:
comment1
comment1
comment2
comment2
comment3
comment4
comment5
comment4
comment2
comment1
comment1
comment2
comment1
我知道如何使用 for...in 语句迭代 2 或 3 层嵌套,但我不知道当嵌套层数未知时该怎么做。
基本上,我需要计算更高级别的所有嵌套字典(方案中的 comment1,对于第二个 comment1 为 7),并在每个级别解析后删除“错误”字典。 请帮忙。
最佳答案
您可以递归地执行此操作。像这样的事情:
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/