Firestore API更改 - 如何解码对象

时间:2018-01-10 22:53:02

标签: ios swift firebase google-cloud-firestore

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

例如,在doco(看似部分更新)中,它说:

  

上一个示例使用getData()来获取内容   将文档作为地图,但使用自定义通常更方便   对象类型。在“添加数据”中,您定义了以前使用的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")
    }
}

正在使用init传递字典。

有人知道Firestore是否会将字典包含在对象解码中吗?从我目前所知,它似乎被删除或无法使用。

1 个答案:

答案 0 :(得分:1)

很抱歉,如果我不清楚你,但如果你想在Swift找到城市对象课,那就在这里。

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
    }

}