drekka
drekka

Reputation: 21883

Firestore API changes - how to decode objects

I'm still new to Firestore and trying to work out how to use it. I've noticed that in several SOF questions and some parts of the Firestore loco it appears that Firestore can return objects of a specific class rather than dictionaries of data.

For example, in the doco (Which appears to be partially updated) it says:

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).

However the code sample directly following it looks to be updated:

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")
    }
}

And is using an init to pass a dictionary.

Does anyone know if Firestore is going to include dictionary to object decoding? From what I can find out at the moment, it appears to be dropped or not available.

Upvotes: 0

Views: 779

Answers (1)

Ego Slayer
Ego Slayer

Reputation: 2067

Sorry if I don't understand you clearly, But if you want to find City Object Class in Swift it's here.

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
    }

}

Upvotes: 1

Related Questions