fireStore type does not match [String:any]

狂风中的少年 提交于 2021-01-29 14:10:49

问题


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 ?


回答1:


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.




回答2:


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)


来源:https://stackoverflow.com/questions/61955190/firestore-type-does-not-match-stringany

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!