如何快速处理具有多个键值的字典?

时间:2018-11-20 20:08:09

标签: swift dictionary

如果我有一个如下图所示的字典,该如何分解这些值,以便分别使用颜色,内容等?如何将字典转换为结构?我不确定从这里去哪里...

(key: "comment2", value: {
    color = grape;
    content = "yeah ";
    date = 563954564;
    icon = referee;
    userName = "That Guy";
})


let comments = messages.childSnapshot(forPath: "comments").value as? [String: Any] ?? [:]



                for comment in comments {

                    struct aComment {
                        let content: String
                        let icon: String
                        let color: String
                        let date: String
                        let userName: String

                        init(comment: [String: Any]) {
                            self.content = comment["content"] as? String ?? ""
                            self.icon = comment["icon"] as? String ?? ""
                            self.color = comment["color"] as? String ?? ""
                            self.date = comment["date"] as? String ?? ""
                            self.userName = comment["userName"] as? String ?? ""
                        }

                    }


                }

1 个答案:

答案 0 :(得分:1)

您可以使用Swift的基本映射方式。例如,在上面的示例中,我们有一个视图结构。首先,我们将向其添加一个init方法。

init(with dictionary: [String: Any]?) {
  guard let dictionary = dictionary else { return }
  color = dictionary["color"] as? String
}

然后像这样映射您的对象:

let view = View(dictionary: data["comment2"])