swift - 如何快速处理具有多个键值的字典?
问题描述
如果我有一个如下所示的字典,我如何分解这些值以便我可以分别使用颜色、内容等?如何将字典转换为结构?我不知道从这里去哪里......
(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 ?? ""
}
}
}
解决方案
您可以使用 Swift 的基本映射方式。例如,我们在上面的示例中有一个视图结构。首先,我们将为其添加一个 init 方法。
init(with dictionary: [String: Any]?) {
guard let dictionary = dictionary else { return }
color = dictionary["color"] as? String
}
然后像这样映射你的对象:
let view = View(dictionary: data["comment2"])
推荐阅读
- xamarin.forms - 在 Xamarin 表单中处理缓慢的页面加载时间
- c# - Pop_Up 模态验证
- jenkins - 无法解析类 XmlParser.parseText
- c++ - 如果指针在 C++ 中为 NULL,则修改它
- android - 无法从 Api 调用中获得响应,它返回 Forbidden 错误
- kotlin - 在单个函数中从多个类中导入成员以构建 kotlin dsl
- php - Nginx 将所有请求从子目录发送到 php-fpm?
- docker - Kubernetes 上的 SEQ 不公开
- html - 剑道不显示任何数据还在mvc中显示一个空白行
- excel - 从 Word VBA 宏以编辑模式从 SharePoint 打开 Excel 工作簿