首页 > 解决方案 > 如何快速处理具有多个键值的字典?

问题描述

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

(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 ?? ""
                        }

                    }


                }

标签: swiftdictionary

解决方案


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

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

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

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

推荐阅读