swift - 如何将 Firestore 文档映射到结构?

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

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

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 中的文档。我想将每个文档映射到它应该是的对象类型;在本例中是一个地址。

例如,我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]) -> Address?' to type '(Dictionary<String, Any>) -> String?'

Cannot convert value of type '(Dictionary<String, Any>) -> String?' to expected argument type '((key: String, value: Any)) -> String?'

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

最佳答案

试试这个:

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 用于当闭包返回可选值时

关于swift - 如何将 Firestore 文档映射到结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50615325/

相关文章:

ios - Swift 发送者 UIButton 更改文本

ios - 为表格 View 单元格图像创建圆形图片

ios - Firebase REST API - 如何观察和监听变化

firebase - 使用 Firebase 实时数据库在 Flutter 中进行分页

firebase - 无法通过 HTTP/REST 错误 403 Forbidden 访问 FireBase 数据库

swift - 两个纬度之间的Firebase查询

node.js - 使用nodejs作为管理员更新firebase中的值

ios - 预加载自定义 UITableViewCell,然后在 tableview 中重新使用它们

ios - Manifest.lock 给出关于 Podfile.lock 的警告,是什么原因造成的?

firebase - 错误在Flutter中检索Firebase集合数时?