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

Jas*_*ltz 2 firebase swift 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
    }
}
Run Code Online (Sandbox Code Playgroud)

我查询了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)
Run Code Online (Sandbox Code Playgroud)

我收到的错误是:

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?'

我确定这很简单,只是不确定该如何解决。:/

dbn*_*dbn 5

尝试这个:

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)
    }
}
Run Code Online (Sandbox Code Playgroud)

另外,flatMap现在不建议使用,compactMap因为闭包返回可选值时有利