【问题标题】:How to handle a dictionary with multiple key values in swift? [closed]如何快速处理具有多个键值的字典? [关闭]
【发布时间】:2018-11-20 20:08:09
【问题描述】:

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

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

                    }


                }

【问题讨论】:

  • 将字典映射到结构体。
  • 如何做到这一点
  • 你被否决了,因为你的问题不清楚,只向我们展示了一些模棱两可的输出,没有向我们展示你是如何解析这个的。 MCVE 会有所帮助。请参阅How do I ask a good question? 但是,在回答您的问题时,我建议您并不想这样做。 “打破价值观”,而是您想要一个模型结构,可以轻松访问您需要的内容。但我们不可能用所提供的信息有意义地回答这个问题。
  • 请搜索。这是非常基本的东西,Stackoverflow 不是代码编写服务。

标签: swift dictionary


【解决方案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"])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-16
    • 2016-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多