首页 > 解决方案 > 如何使用嵌套数据创建结构

问题描述

Firestore 文档结构的照片:

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)}}

标签: iosswiftfirebasegoogle-cloud-firestore

解决方案


你的字典有 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)}
}

推荐阅读