fireStore type does not match [String:any]

jumping into FireStore following the official documentation, trying to connect a Struct to Firestore/setdata functions, according to the documentation, Cloud Firestore converts the objects to supported data types and can handle custom classes

so the struct goes as follow :

public struct City: Codable {

let name: String
let state: String?
let country: String?
let isCapital: Bool?
let population: Int64?

enum CodingKeys: String, CodingKey {
    case name
    case state
    case country
    case isCapital = "capital"
    case population
}

}

and uploading data as follow. Firestore wants a [String: Any] type of data :

 let city = City(name: "Los Angeles",
                state: "CA",
                country: "USA",
                isCapital: false,
                population: 5000000)

do {
    try db.collection("cities").document("LA").setData(city) // <--- Cannot convert value of type 'postData' to expected argument type '[String : Any]'

} catch let error { 
    print("Error writing city to Firestore: \(error)")
}

any idea how to solve this ?

2 answers

  • answered 2020-05-22 12:43 Kuhlemann

    I think setting the data should look more like this:

            db.collection("cities").document("LA").setData([
                cityName: city.name,
                cityState: city.state,
                // And so on...
            ])
    

    Those are Key:Value-Pairs. On the left side is the field name in FireStore and the right side the value that should be written in it.

  • answered 2020-05-22 21:23 Yann Massard

    so the only way I found to connect custom Structs (or classes) is a bit ugly, but it works but defining the struct as follow

    public struct City: Codable {
    
    let name: String
    let state: String
    
    var DataToPass : [String:Any] {
        return [
    
            "name" = self.name
            "state" = self.state
    
        ]
    
    
    }
    

    and then simply pass it to FStore using datapass :

    let city = City(name: "Los Angeles",
                    state: "CA")
    db.collection("cities").document("LA").setData(city.dataToPass)