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

时间:2018-05-31 01:16:09

标签: 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中查询了文档。我想将每个文档映射到它应该是的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]) -> 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?'

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

1 个答案:

答案 0 :(得分:4)

试试这个:

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