【问题标题】:Firestore API changes - how to decode objectsFirestore API 更改 - 如何解码对象
【发布时间】:2018-01-10 22:53:02
【问题描述】:

我还是 Firestore 的新手,并试图弄清楚如何使用它。我注意到在几个 SOF 问题和 Firestore loco 的某些部分中,Firestore 似乎可以返回特定类的对象而不是数据字典。

例如,在文档中(似乎已部分更新)它说:

前面的例子使用getData()来获取 文档作为地图,但使用自定义通常更方便 对象类型。在 Add Data 中,您定义了一个 City 类 定义每个城市。您可以将文档转回 City 对象 致电.getData(City.class)

但是,紧随其后的代码示例似乎已更新:

let docRef = db.collection("cities").document("BJ")

docRef.getDocument { (document, error) in
    if let city = document.flatMap({ City(dictionary: $0.data()) }) {
        print("City: \(city)")
    } else {
        print("Document does not exist")
    }
}

并且正在使用初始化来传递字典。

有谁知道 Firestore 是否会包含字典到对象解码?据我目前所知,它似乎已被删除或不可用。

【问题讨论】:

    标签: ios swift firebase google-cloud-firestore


    【解决方案1】:

    对不起,如果我没有清楚地理解你,但是如果你想在 Swift 中找到 City Object Class,它就在这里。

    struct City {
    
        let name: String
        let state: String?
        let country: String?
        let capital: Bool?
        let population: Int64?
    
        init?(dictionary: [String: Any]) {
            guard let name = dictionary["name"] as? String else { return nil }
            self.name = name
    
            self.state = dictionary["state"] as? String
            self.country = dictionary["country"] as? String
            self.capital = dictionary["capital"] as? Bool
            self.population = dictionary["population"] as? Int64
        }
    
    }
    

    【讨论】:

    • 感谢您的回复。我要问的是,Firestore 是否具有根据文档将数据映射到对象的内置功能。还是我们必须按照示例代码自己做。
    猜你喜欢
    • 1970-01-01
    • 2018-09-01
    • 2018-09-09
    • 1970-01-01
    • 2019-03-30
    • 2021-02-02
    • 2023-02-26
    相关资源
    最近更新 更多