【问题标题】:How can I map a Firestore document to a struct?如何将 Firestore 文档映射到结构?
【发布时间】:2018-11-09 22:29:25
【问题描述】:

我有一个看起来像这样的模型:

import Foundation
import CoreLocation
struct Address {

    //    let dateCreated: Date
    let street: String?
    let city: String?
    let state: String?
    let postalCode: String?
    let country: String?
    let ISOCountryCode: String?
    var coordinates: CLLocationCoordinate2D?
    var active: Bool?

    init?(dictionary: [String : Any]) {
        self.street = dictionary["street"] as? String
        self.city = dictionary["city"] as? String
        self.state = dictionary["state"] as? String
        self.postalCode = dictionary["postalCode"] as? String
        self.country = dictionary["country"] as? String
        self.ISOCountryCode = dictionary["ISOCountryCode"] as? String
        self.coordinates = dictionary["coordinates"] as? CLLocationCoordinate2D
        self.active = dictionary["active"] as? Bool
    }
}

我有一个对 Firebase Firestore 中文档的查询。我想将每个文档映射到它应该是的 Object 类型;在这种情况下是地址。

例如,我 getDocuments 然后我开始循环遍历 snapshot.documents 中的每个文档。我将文档映射到一种对象的代码(不起作用)如下所示:

let closure: (Dictionary<String, Any>) -> String?
closure = { dictionary in
    return Address(dictionary: dictionary)
}
var addresses = [Address]()

addresses = document.data().flatMap(closure)

我收到的错误是:

Cannot assign value of type '([String : Any]) -&gt; Address?' to type '(Dictionary&lt;String, Any&gt;) -&gt; String?'

Cannot convert value of type '(Dictionary&lt;String, Any&gt;) -&gt; String?' to expected argument type '((key: String, value: Any)) -&gt; String?'

我确定这很简单,我只是不确定我能做些什么来解决它。 :/

【问题讨论】:

    标签: swift firebase firebase-realtime-database google-cloud-firestore


    【解决方案1】:

    试试这个:

    func getAddresses(at path: String, completion: @escaping (([Address]) -> ())) {
        let data = Firestore.firestore().collection(path)
        data.getDocuments { (snapshot, error) in
            let dictionaries = snapshot?.documents.compactMap({$0.data()}) ?? []
            let addresses = dictionaries.compactMap({Address($0)})
            completion(addresses)
        }
    }
    

    此外,flatMap 现在已被弃用,而在闭包返回可选值时支持 compactMap

    【讨论】:

    • 您好,您如何也可以将 documentID 保存在字典中?谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-03
    • 2020-04-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-26
    相关资源
    最近更新 更多