我对 Firestore 还是个新手,正在尝试了解如何使用它。我注意到在几个 SOF 问题和 Firestore loco 的某些部分中,Firestore 似乎可以返回特定类的对象而不是数据字典。
例如,在 doco(似乎已部分更新)中它说:
The previous example used
getData()
to get the contents of the document as a map, but it's often more convenient to use a custom object type. In Add Data, you defined a City class that you used to define each city. You can turn your document back into a City object by calling.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 是否会在对象解码中包含字典?据我目前所知,它似乎已删除或不可用。
最佳答案
抱歉,如果我没听清楚,但如果你想在 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
}
}
关于ios - Firestore API 更改 - 如何解码对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48197401/