ios - 如何使用嵌套数据创建结构
问题描述
Firestore 文档结构的照片:
我正在尝试使用一种结构来创建一个数据模型,该模型将显示我来自 Firestore 的数据。但我对如何获取我的映射/嵌套数据有点困惑。我确信它很简单,但我觉得我错过了关于 Swift 的一些基础知识。我的代码在下面,我很确定我必须检索的名字和姓氏是错误的。我了解如何通过相同的方式获取表面数据,但是当它是数组或映射时,我似乎无法理解语法。
protocol DocumentSerializable {
init?(dictionary:[String:Any])
}
struct ItemModel{
var merchant: String?
var first: String?
var last: String?
var dictionary:[String:Any]{
return [
"merchant":
["first": first,
"last": last
]
]
}
}
extension ItemModel : DocumentSerializable {
init?(dictionary: [String : Any]) {
guard let merchant = dictionary["merchant"] as? String,
let first = dictionary["first"] as? String,
let last = dictionary["last"] as? String
else {return nil}
self.init(merchant:merchant, first:first, last:last)}}
解决方案
你的字典有 Key : "merchant" 和 value : ["first": first, "last": last],所以下面的 "merchant" 变量是一个字典,下面的访问是有意义的:
extension ItemModel : DocumentSerializable {
init?(dictionary: [String : Any]) {
guard let merchant = dictionary["merchant"] as? Dictionary,
let first = merchant["first"] as? String,
let last = merchant["last"] as? String
else {return nil}
self.init(merchant:"merchant", first:first, last:last)}
}
推荐阅读
- android - 在 android kotlin 中将 Cloud Firestore 数据预先写入纯文本
- python - 无法使用 JWK 签名创建 JWT
- python - 查找列表中唯一的唯一值
- php - 使用多维矩阵生成多个字符串
- python - 调整脚本以计算执行的操作
- regex - 使用正则表达式捕获单个表情符号
- html - fb:app_id 还需要吗?
- node.js - 是否有解决方案将项目推送到节点 js 中的异步函数中的数组?
- docker - 在 WSL2 权限被拒绝的詹金斯容器内运行 docker 命令
- data-visualization - 在 Tableau 中规范化表格